Progress28.ru

IT Новости


09ae9cb0
4 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Php datetime сравнение

Сравнение даты и времени при помощи PHP функции StrToTime ()

В PHP можно легко создать удобочитаемую дату или время, используя функцию Date() . Эта функция принимает два аргумента: допустимый формат даты и метку времени Unix ( если ее не указывать, функция возвратит текущую дату/время ).

Приведенный выше пример прекрасно подходит для отображения дат и времени. Но когда дело доходит до PHP сравнения дат, использовать удобные для чтения строки — не самый надежный способ. Намного эффективнее сравнить временные метки. Метка времени Unix содержит количество секунд между 1 января 1970 00:00:00 GMT и указанным временем. Это означает, что можно сравнивать даты вплоть до секунд.

Чтобы использовать функцию date() для возврата конкретной даты необходима метка времени, так что сначала потребуется создать ее. Это можно сделать с помощью функций mktime() или strotime() . Обе функции возвращают метку времени Unix , но при этом принимают различные аргументы.

Функция mktime() требует, чтобы дата и время были переданы ей в виде отдельных сегментов ( часы, минуты, секунды, месяц, день, год ):

В свою очередь функция strtotime() может преобразовать текстовое представление даты/времени в метку времени:

Если при PHP сравнении даты с текущей функция strtotime() получает дату/время, в которых день и месяц располагаются перед годом, эта запись будет интерпретироваться по-разному, в зависимости от используемого разделителя. При использовании косой черты в качестве разделителя функция возвратит метку времени в американском формате ( м/д/г ). При использовании в качестве разделителя тире или точки функция возвратит метку в европейском формате ( д-м-г ).

Как можно увидеть ниже, первая метка времени отличается от двух последних:

Функции mktime() и strtotime() возвращают одинаковый результат. Часто текстовое представление даты и времени (‘ 2016-01-01 ‘) хранится в базе данных и считывается из нее через HTML-форму . Например, при помощи библиотеки jQuery datepicker , которая идеально подходит для использования функции strtotime() .

Прежде чем осуществлять сравнение двух дат в PHP , важно убедиться, что временные метки созданы с помощью одного и того же формата. Можно воспользоваться функцией mktime() . Ее преимущество заключается в том, что она намного строже в отношении передаваемой ей даты или время.

Важным преимуществом использования функции strtotime() является гибкость и простота, с которой можно добавить время или вычесть из него:

Пример, показанный ниже, демонстрирует PHP сравнение даты и операции с использованием функции strtotime() . В нем создается массив дат в заданном диапазоне в соответствии с определенным временным интервалом. Функция print_r() выводит результирующий массив, который выглядит следующим образом:

При сравнении двух дат в PHP внутри цикла while время ( в данном случае семь дней ) добавляется к дате начала и производится проверка, чтобы убедиться больше ли полученная временная метка, чем временная метка даты начала.

Если это не так, новая дата добавляется в массив $DateRange , пока цикл не закончится:

Я использовал оператор switch , чтобы определить несколько различных вариантов временного интервала. Это было сделано для того, чтобы показать, как интуитивные « временные » строки использовались для управления временной меткой с помощью функции strtotime() . В документации по PHP приводятся дополнительные примеры.

Данная публикация представляет собой перевод статьи « Compare Date and Time With PHP strtotime() | Quick Reference Tutorial » , подготовленной дружной командой проекта Интернет-технологии.ру

DateTime::diff

DateTimeInterface::diff

(PHP 5 >= 5.3.0, PHP 7)

DateTime::diff — DateTimeImmutable::diff — DateTimeInterface::diff — date_diff — Возвращает разницу между двумя объектами DateTime

Описание

Возвращает разницу между двумя объектами DateTimeInterface.

Список параметров

Дата и время для сравнения.

Используется, чтобы вернуть абсолютную разницу.

Возвращаемые значения

DateInterval объект представляет разницу между двумя датами или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::diff()

Результат выполнения данных примеров:

Пример #2 Сравнение объектов DateTime

С версии PHP 5.2.2 объекты DateTime могут сравниваться при помощи операторов сравнения.

= new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );

var_dump ( $date1 == $date2 );
var_dump ( $date1 $date2 );
var_dump ( $date1 > $date2 );
?>

Результат выполнения данного примера:

Смотрите также

  • DateInterval::format() — Форматирует интервал
  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime

User Contributed Notes 28 notes

It is worth noting, IMO, and it is implied in the docs but not explicitly stated, that the object on which diff is called is subtracted from the object that is passed to diff.

i.e. $now->diff($tomorrow) is positive.

Be careful using:

$date1 = new DateTime(‘now’);
$date2 = new DateTime(‘tomorrow’);

$interval = date_diff($date1, $date2);

echo $interval->format(‘In %a days’);

In some situations, this won’t say «in 1 days», but «in 0 days».
I think this is because «now» is the current time, while «tomorrow» is the current day +1 but at a default time, lets say:

Now: 08:00pm, 01.01.2015
Tomorrow: 00:00am, 02.01.2015

In this case, the difference is not 24 hour, so it will says 0 days.

Better use «today», which should also use a default value like:

Today: 00:00am, 01.01.2015
Tomorrow: 00:00am, 02.01.2015

which now is 24 hour and represents 1 day.

This may sound logical and many will say «of course, this is right», but if you use it in a naiv way (like I did without thinking), you can come to this moment and facepalm yourself.

Conclusion: «Now» is «Today», but in a different clock time, but still the same day!

Читать еще:  Php trim string

After wrestling with DateTime::diff for a while it finally dawned on me the problem was both in the formatting of the input string and the formatting of the output.

The task was to calculate the duration between two date/times.

1. Make sure you have a valid date variable. Both of these strings are valid:

$strStart = ‘2013-06-19 18:25’ ;
$strEnd = ’06/19/13 21:47′ ;

?>

2. Next convert the string to a date variable

= new DateTime ( $strStart );
$dteEnd = new DateTime ( $strEnd );

3. Calculate the difference

= $dteStart -> diff ( $dteEnd );

4. Format the output

print $dteDiff -> format ( «%H:%I:%S» );

[Modified by moderator for clarify]

Be careful, the behaviour depends on the time zones in a weird way.

function printDiff ( $tz ) <
$d1 = new DateTime ( «2015-06-01» , new DateTimeZone ( $tz ));
$d2 = new DateTime ( «2015-07-01» , new DateTimeZone ( $tz ));
$diff = $d1 -> diff ( $d2 );
print( $diff -> format ( «Year: %Y Month: %M Day: %D» ). PHP_EOL );
>
printDiff ( «UTC» );
printDiff ( «Australia/Melbourne» );
?>

The result is different:

Year: 00 Month: 01 Day: 00
Year: 00 Month: 00 Day: 30

If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval.

The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date. If the date occurs in the past (is negative/inverted), it suffixes it with ‘ago’.

function pluralize ( $count , $text )
<
return $count . ( ( $count == 1 ) ? ( » $text » ) : ( » $ < text >s» ) );
>

function ago ( $datetime )
<
$interval = date_create ( ‘now’ )-> diff ( $datetime );
$suffix = ( $interval -> invert ? ‘ ago’ : » );
if ( $v = $interval -> y >= 1 ) return pluralize ( $interval -> y , ‘year’ ) . $suffix ;
if ( $v = $interval -> m >= 1 ) return pluralize ( $interval -> m , ‘month’ ) . $suffix ;
if ( $v = $interval -> d >= 1 ) return pluralize ( $interval -> d , ‘day’ ) . $suffix ;
if ( $v = $interval -> h >= 1 ) return pluralize ( $interval -> h , ‘hour’ ) . $suffix ;
if ( $v = $interval -> i >= 1 ) return pluralize ( $interval -> i , ‘minute’ ) . $suffix ;
return pluralize ( $interval -> s , ‘second’ ) . $suffix ;
>
?>

It seems that while DateTime in general does preserve microseconds, DateTime::diff doesn’t appear to account for it when comparing.

= ‘2014-03-18 10:34:09.939’ ;
$val2 = ‘2014-03-18 10:34:09.940’ ;

$datetime1 = new DateTime ( $val1 );
$datetime2 = new DateTime ( $val2 );
echo «

» ;
var_dump ( $datetime1 -> diff ( $datetime2 ));

if( $datetime1 > $datetime2 )
echo «1 is bigger» ;
else
echo «2 is bigger» ;
?>

The var_dump shows that there is no «u» element, and «2 is bigger» is echoed.

To work around this apparent limitation/oversight, you have to additionally compare using DateTime::format.

if( $datetime1 > $datetime2 )
echo «1 is bigger» ;
else if ( $datetime1 -> format ( ‘u’ ) > $datetime2 -> format ( ‘u’ ))
echo «1 is bigger» ;
else
echo «2 is bigger» ;
?>

Warning, there’s a bug on windows platforms: the result is always 6015 days (and not 42. )

Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:

function get_timespan_string ( $older , $newer ) <
$Y1 = $older -> format ( ‘Y’ );
$Y2 = $newer -> format ( ‘Y’ );
$Y = $Y2 — $Y1 ;

$m1 = $older -> format ( ‘m’ );
$m2 = $newer -> format ( ‘m’ );
$m = $m2 — $m1 ;

$d1 = $older -> format ( ‘d’ );
$d2 = $newer -> format ( ‘d’ );
$d = $d2 — $d1 ;

$H1 = $older -> format ( ‘H’ );
$H2 = $newer -> format ( ‘H’ );
$H = $H2 — $H1 ;

$i1 = $older -> format ( ‘i’ );
$i2 = $newer -> format ( ‘i’ );
$i = $i2 — $i1 ;

$s1 = $older -> format ( ‘s’ );
$s2 = $newer -> format ( ‘s’ );
$s = $s2 — $s1 ;

if( $s 0 ) <
$i = $i — 1 ;
$s = $s + 60 ;
>
if( $i 0 ) <
$H = $H — 1 ;
$i = $i + 60 ;
>
if( $H 0 ) <
$d = $d — 1 ;
$H = $H + 24 ;
>
if( $d 0 ) <
$m = $m — 1 ;
$d = $d + get_days_for_previous_month ( $m2 , $Y2 );
>
if( $m 0 ) <
$Y = $Y — 1 ;
$m = $m + 12 ;
>
$timespan_string = create_timespan_string ( $Y , $m , $d , $H , $i , $s );
return $timespan_string ;
>

function get_days_for_previous_month ( $current_month , $current_year ) <
$previous_month = $current_month — 1 ;
if( $current_month == 1 ) <
$current_year = $current_year — 1 ; //going from January to previous December
$previous_month = 12 ;
>
if( $previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4 ) <
return 30 ;
>
else if( $previous_month == 2 ) <
if(( $current_year % 4 ) == 0 ) < //remainder 0 for leap years
return 29 ;
>
else <
return 28 ;
>
>
else <
return 31 ;
>
>

function create_timespan_string ( $Y , $m , $d , $H , $i , $s )
<
$timespan_string = » ;
$found_first_diff = false ;
if( $Y >= 1 ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $Y , ‘year’ ). ‘ ‘ ;
>
if( $m >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $m , ‘month’ ). ‘ ‘ ;
>
if( $d >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $d , ‘day’ ). ‘ ‘ ;
>
if( $H >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $H , ‘hour’ ). ‘ ‘ ;
>
if( $i >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $i , ‘minute’ ). ‘ ‘ ;
>
if( $found_first_diff ) <
$timespan_string .= ‘and ‘ ;
>
$timespan_string .= pluralize ( $s , ‘second’ );
return $timespan_string ;
>

function pluralize ( $count , $text )
<
return $count . ( ( $count == 1 ) ? ( » $text » ) : ( » $ < text >s» ) );
>
?>

Php datetime сравнение

Начиная с версии 5.2 в PHP появился такой тип данных как DateTime. Попробуем в этой статье разобраться почему лучше использовать его вместо старых функций date() и time().

Читать еще:  Php warning division by zero in

Функция date() используется для строкового отображения даты/времени. Функция принимает два параметра, 1-ый — формат возвращаемой строки, а второй — само значение даты. По умолчанию второй параметр принимает значение текущего момента времени, либо можно указать отметку времени в unix формате (timestamp).

Функция time() возвращает текущее время в unix формате (timestamp).

Datetime()

Объект Datetime впервые был представлен в PHP версии 5.2, он содержит в себе множество вспомогательных объектов, для решения проблем, с которыми вам приходилось сталкиваться при использовании функций date() и time(). Также был представлен объект DateTimeZone, который управляет часовым поясом, объект DateInterval соответствует интервалу времени (например 2 дня) от настоящего момента, DatePeriod показывает разницу во времени между двумя разными датами. Основное преимущество использования DateTime перед старыми функциями заключается в том, что значения дат проще изменять. Если вы хотите получить значение времени и даты при помощи функции date(), то вы напишите следующее:

А вот пример для установки часового пояса:

Проблема возникает при необходимости изменить или сравнить две отметки времени, DateTime имеет методы modify() и diff() упрощающие задачу. Преимущества DateTime проявляются когда вы манипулируете значениями дат.

Сначала объект надо инициализировать

Конструктор этого класса принимает два параметра. Первый — значение времени, вы можете использовать строку в формате функции date, время в формате Unix, интервал или период. Второй параметр — часовой пояс.

Вывод форматированной даты

Объект DateTime может работать также как и функция date, всего лишь необходимо вызвать метод format() указав формат возвращаемой строки.

Вывод отметки времени (timestamp)

Для вывода отметки времени в формате Unix существует метод getTimestamp() .

Изменение времени

Для изменения значения времени существует метод setTime() .

Изменение метки timestamp

Для этого придуман метод setTimestamp() .

Установка часового пояса

Второй параметр при создании объекта — DateTimeZone, он позволяет назначить часовой пояс нашему объекту. Это означает, что мы сможем легко сравнивать два значения времени из разных часовых поясов и получать корректную разницу.

Также для установки этого значения существует метод setTimezone() .

Полный список часовых поясов можно просмотреть на php.net.

Как добавить дни к значению даты

Для изменения значения даты в объекте DateTime можно использовать метод modify(). Он принимает в качестве параметра строковое значение дней, месяцев, года. Например, если хотите прибавить несколько дней, например 3 дня, один месяц и один год:

Сравнение двух дат

Код выше даст нам разницу двух дат в виде DateInterval.

Конвертация номера месяца и имени месяца

Довольно часто приходится получать имя месяца из его порядкового номера, для этого всего лишь нужно указать формат “F” в качестве первого параметра

При использовании класса DateTime можно применить метод format() .

Получаем количество недель в месяце

Следующий пример поможет вам получить количество недель в определенном месяце года.

DateTime::diff

DateTimeInterface::diff

(PHP 5 >= 5.3.0, PHP 7)

DateTime::diff — DateTimeImmutable::diff — DateTimeInterface::diff — date_diff — Возвращает разницу между двумя DateTime объектами

Описание

Возвращает разницу между двумя DateTimeInterface объектами.

Список параметров

Дата и время для сравнения.

Используется, чтобы вернуть абсолютную разницу.

Возвращаемые значения

DateInterval объект представляет разницу между двумя датами или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Пример использования DateTime::diff()

Результат выполнения данных примеров:

Пример #2 Сравнение объектов DateTime

В PHP 5.2.2 объекты DateTime сравнивались при помощи операторов сравнения.

= new DateTime ( «now» );
$date2 = new DateTime ( «tomorrow» );

var_dump ( $date1 == $date2 );
var_dump ( $date1 $date2 );
var_dump ( $date1 > $date2 );
?>

Результат выполнения данного примера:

Смотрите также

  • DateInterval::format() — Форматирует интервал
  • DateTime::add() — Добавляет заданное количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime
  • DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime

Коментарии

You don’t need to calculate the exact difference if you just want to know what date comes earlier:

$d1 = new DateTime ( ‘1492-01-01’ );
$d2 = new DateTime ( ‘1492-12-31’ );

var_dump ( $d1 $d2 );
var_dump ( $d1 > $d2 );
var_dump ( $d1 == $d2 );

For those like me who don’t yet have PHP 5.3 installed on their host, here’s a simple alternative to get the number of days between two dates in the format ‘2010-3-23’ or similar acceptable to strtotime(). You need PHP 5.2.

function date_diff ( $date1 , $date2 ) <
$current = $date1 ;
$datetime2 = date_create ( $date2 );
$count = 0 ;
while( date_create ( $current ) $datetime2 ) <
$current = gmdate ( «Y-m-d» , strtotime ( «+1 day» , strtotime ( $current )));
$count ++;
>
return $count ;
>

echo ( date_diff ( ‘2010-3-9’ , ‘2011-4-10’ ). » days
» );
?>

If you want to quickly scan through the resulting intervals, you can use the undocumented properties of DateInterval.

The function below returns a single number of years, months, days, hours, minutes or seconds between the current date and the provided date. If the date occurs in the past (is negative/inverted), it suffixes it with ‘ago’.

function pluralize ( $count , $text )
<
return $count . ( ( $count == 1 ) ? ( » $text» ) : ( » $s» ) );
>

function ago ( $datetime )
<
$interval = date_create ( ‘now’ )-> diff ( $datetime );
$suffix = ( $interval -> invert ? ‘ ago’ : » );
if ( $v = $interval -> y >= 1 ) return pluralize ( $interval -> y , ‘year’ ) . $suffix ;
if ( $v = $interval -> m >= 1 ) return pluralize ( $interval -> m , ‘month’ ) . $suffix ;
if ( $v = $interval -> d >= 1 ) return pluralize ( $interval -> d , ‘day’ ) . $suffix ;
if ( $v = $interval -> h >= 1 ) return pluralize ( $interval -> h , ‘hour’ ) . $suffix ;
if ( $v = $interval -> i >= 1 ) return pluralize ( $interval -> i , ‘minute’ ) . $suffix ;
return pluralize ( $interval -> s , ‘second’ ) . $suffix ;
>
?>

Читать еще:  Php num rows

I found that DateTime::diff isn’t as accurate as I thought. I calculated the age gap between now and a birthdate from before 1970 (unix epoch). Here’s what I got:

Given today is January 21st, 2011:

// birthdate format is YYYY-MM-DD
$birth = new DateTime ( ‘1966-01-21’ );
$today = new DateTime ();
$diff = $birth -> diff ( $today );
echo $diff -> format ( ‘%y’ ); // will output 45

$birth = new DateTime ( ‘1966-01-23’ );
$today = new DateTime ();
$diff = $birth -> diff ( $today );
echo $diff -> format ( ‘%y’ ); // will output 45 wrongly

$birth = new DateTime ( ‘1966-01-24’ ); // three days difference!
$today = new DateTime ();
$diff = $birth -> diff ( $today );
echo $diff -> format ( ‘%y’ ); // will output 44 — correct
?>

When calculating with the date() function it was more accurate (didn’t use seconds/hours for comparison).

Note that 3 days may be a lot if you want to create invoices and have to check against a given age to determine if the customer is chargable for taxes and so on.

If someone also found this behaviour I’d like to hear about it — give me a quick mail at schindhelm (at) gmail (dot) com.
Thanks.

Warning, there’s a bug on windows platforms: the result is always 6015 days (and not 42. )

I was looking for a way to output X number of days from a given date and didn’t find exactly what I was looking for. But I got this working. I hope this helps you.

This will output the number of days,months, or years difference between NOW and a April 1st, 2011.

= new DateTime ( ‘2011-04-01’ );
$date2 = new DateTime ( «now» );
$interval = $date1 -> diff ( $date2 );
$years = $interval -> format ( ‘%y’ );
$months = $interval -> format ( ‘%m’ );
$days = $interval -> format ( ‘%d’ );
if( $years != 0 ) <
$ago = $years . ‘ year(s) ago’ ;
>else <
$ago = ( $months == 0 ? $days . ‘ day(s) ago’ : $months . ‘ month(s) ago’ );
>
echo $ago ;
?>

If I used today, 2011-05-16 as $date1, I could return all 0’s in the format. For example.

= new DateTime ( ‘2011-05-161’ );
$date2 = new DateTime ( «now» );
$interval = $date1 -> diff ( $date2 );
$diff = $interval -> format ( ‘%y-%m-%d’ );
echo $diff ; //Today, this will output 0-0-0
?>

$dateTime = new DateTime(‘2011-08-01 00:00:00’);
echo $dateTime->diff(new DateTime(‘2011-10-01 00:00:01’))->format(‘%m’);

will return 1, instead of 2 .

I needed to get the exact number of days between 2 dates and was relying on the this diff function, but found that I was getting a peculiar result with:

= new DateTime ( date ( ‘2011-11-09’ ));
$appt = new DateTime ( date ( ‘2011-12-09’ ));
$days_until_appt = $appt -> diff ( $today )-> d ;
?>

This was returning 0 because it was exactly one month.

I had to end up using :

= $appt -> diff ( $today )-> days ;
?>

to get 30.

Though I found a number of people who ran into the issue of 5.2 and lower not supporting this function, I was unable to find any solid examples to get around it. Therefore I hope this can help some others:

function get_timespan_string ( $older , $newer ) <
$Y1 = $older -> format ( ‘Y’ );
$Y2 = $newer -> format ( ‘Y’ );
$Y = $Y2 — $Y1 ;

$m1 = $older -> format ( ‘m’ );
$m2 = $newer -> format ( ‘m’ );
$m = $m2 — $m1 ;

$d1 = $older -> format ( ‘d’ );
$d2 = $newer -> format ( ‘d’ );
$d = $d2 — $d1 ;

$H1 = $older -> format ( ‘H’ );
$H2 = $newer -> format ( ‘H’ );
$H = $H2 — $H1 ;

$i1 = $older -> format ( ‘i’ );
$i2 = $newer -> format ( ‘i’ );
$i = $i2 — $i1 ;

$s1 = $older -> format ( ‘s’ );
$s2 = $newer -> format ( ‘s’ );
$s = $s2 — $s1 ;

if( $s 0 ) <
$i = $i — 1 ;
$s = $s + 60 ;
>
if( $i 0 ) <
$H = $H — 1 ;
$i = $i + 60 ;
>
if( $H 0 ) <
$d = $d — 1 ;
$H = $H + 24 ;
>
if( $d 0 ) <
$m = $m — 1 ;
$d = $d + get_days_for_previous_month ( $m2 , $Y2 );
>
if( $m 0 ) <
$Y = $Y — 1 ;
$m = $m + 12 ;
>
$timespan_string = create_timespan_string ( $Y , $m , $d , $H , $i , $s );
return $timespan_string ;
>

function get_days_for_previous_month ( $current_month , $current_year ) <
$previous_month = $current_month — 1 ;
if( $current_month == 1 ) <
$current_year = $current_year — 1 ; //going from January to previous December
$previous_month = 12 ;
>
if( $previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4 ) <
return 30 ;
>
else if( $previous_month == 2 ) <
if(( $current_year % 4 ) == 0 ) < //remainder 0 for leap years
return 29 ;
>
else <
return 28 ;
>
>
else <
return 31 ;
>
>

function create_timespan_string ( $Y , $m , $d , $H , $i , $s )
<
$timespan_string = » ;
$found_first_diff = false ;
if( $Y >= 1 ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $Y , ‘year’ ). ‘ ‘ ;
>
if( $m >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $m , ‘month’ ). ‘ ‘ ;
>
if( $d >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $d , ‘day’ ). ‘ ‘ ;
>
if( $H >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $H , ‘hour’ ). ‘ ‘ ;
>
if( $i >= 1 || $found_first_diff ) <
$found_first_diff = true ;
$timespan_string .= pluralize ( $i , ‘minute’ ). ‘ ‘ ;
>
if( $found_first_diff ) <
$timespan_string .= ‘and ‘ ;
>
$timespan_string .= pluralize ( $s , ‘second’ );
return $timespan_string ;
>

function pluralize ( $count , $text )
<
return $count . ( ( $count == 1 ) ? ( » $text» ) : ( » $s» ) );
>
?>

Ссылка на основную публикацию