Php strtotime в днях

PHP strtotime() Function

Parse English textual datetimes into Unix timestamps:

echo(strtotime(«now») . «
«);
echo(strtotime(«3 October 2005») . «
«);
echo(strtotime(«+5 hours») . «
«);
echo(strtotime(«+1 week») . «
«);
echo(strtotime(«+1 week 3 days 7 hours 5 seconds») . «
«);
echo(strtotime(«next Monday») . «
«);
echo(strtotime(«last Sunday»));
?>

Definition and Usage

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator is a slash (/), then the American m/d/y is assumed. If the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. To avoid potential errors, you should YYYY-MM-DD dates or date_create_from_format() when possible.

Syntax

Parameter Values

Parameter Description
time Required. Specifies a date/time string
now Optional. Specifies the timestamp used as a base for the calculation of relative dates

Technical Details

Return Value: Returns a timestamp on success. FALSE on failure
PHP Version: 4+
PHP Changelog: PHP 5.3.0: Relative time formats such as this week, previous week, last week, and next week now interprets a week period of Monday through Sunday, rather then a 7-day period relative to the current date/time
PHP 5.3.0: Now 24:00 is a valid format
PHP 5.2.7: In earlier versions, if requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month it would incorrectly add one week to the returned timestamp. This has been corrected now
PHP 5.1.0: Returns FALSE on failure (earlier versions returns -1), and issues E_STRICT and E_NOTICE time zone errors
PHP 5.0.2: Now correctly computes «now» and other relative times from current time, not from today’s midnight
PHP 5.0.0: Allows microseconds (but they are ignored)
Читайте также:  Gpg error https packages sury org php buster inrelease

❮ PHP Date/Time Reference

Источник

strtotime

Первым параметром функции должна быть строка с датой на английском языке, которая будет преобразована в метку времени Unix (количество секунд, прошедших с 1 января 1970 года 00:00:00 UTC) относительно метки времени, переданной в baseTimestamp , или текущего времени, если аргумент baseTimestamp опущен. Разбор строки даты определён в разделе Форматы даты и времени и содержит несколько аспектов. Настоятельно рекомендуется с ними ознакомиться.

Временная метка Unix, которую возвращает эта функция, не содержит информацию о часовых поясах. Для выполнения расчётов с информацией о дате/времени вы должны использовать более подходящий DateTimeImmutable .

Каждый параметр функции использует временную метку по умолчанию, пока она не указана в этом параметре напрямую. Будьте внимательны и не используйте различные временные метки в параметрах, если на то нет прямой необходимости. Обратите внимание на date_default_timezone_get() для задания часового пояса различными способами.

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

Строка даты/времени. Объяснение корректных форматов дано в разделе Форматы даты и времени.

Временная метка, используемая в качестве базы для вычисления относительных дат.

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

Возвращает временную метку в случае успешного выполнения, иначе возвращается false .

Ошибки

Каждый вызов к функциям даты/времени при неправильных настройках часового пояса сгенерирует ошибку уровня E_WARNING , если часовой пояс некорректный. Смотрите также date_default_timezone_set()

Список изменений

Версия Описание
8.0.0 baseTimestamp теперь допускает значение null.

Примеры

Пример #1 Пример использования функции strtotime()

echo strtotime ( «now» ), «\n» ;
echo strtotime ( «10 September 2000» ), «\n» ;
echo strtotime ( «+1 day» ), «\n» ;
echo strtotime ( «+1 week» ), «\n» ;
echo strtotime ( «+1 week 2 days 4 hours 2 seconds» ), «\n» ;
echo strtotime ( «next Thursday» ), «\n» ;
echo strtotime ( «last Monday» ), «\n» ;
?>

Пример #2 Проверка ошибок

if (( $timestamp = strtotime ( $str )) === false ) echo «Строка ( $str ) недопустима» ;
> else echo » $str = color: #007700″>. date ( ‘l dS \o\f F Y h:i:s A’ , $timestamp );
>
?>

Примечания

Замечание:

«Относительная» дата в данном случае также означает, что если конкретный компонент метки даты/времени не указан, он будет взят дословно из параметр baseTimestamp . То есть, strtotime(‘February’) , если его запустить 31 мая 2022 года, будет интерпретирован как 31 февраля 2022 , что перенесётся в метку времени 3 марта (в високосный год будет 2 марта ). Использование strtotime(‘1 February’) или strtotime(‘first day of February’) позволит избежать этой проблемы.

Замечание:

Если количество лет указано двумя цифрами, то значения 00-69 будут считаться 2000-2069, а 70-99 — 1970-1999. Смотрите также замечания ниже о возможных различиях на 32-битных системах (допустимые даты заканчиваются 2038-01-19 03:14:07).

Замечание:

Корректным диапазоном временных меток обычно являются даты с 13 декабря 1901 20:45:54 UTC по 19 января 2038 03:14:07 UTC. (Эти даты соответствуют минимальному и максимальному значению 32-битового знакового целого).

В 64-битных версиях PHP корректный диапазон временных меток фактически бесконечен, так как 64 битов хватит для представления приблизительно 293 миллиарда лет в обоих направлениях.

Замечание:

Не рекомендуется использовать эту функцию для математических операций. Целесообразно использовать DateTime::add() и DateTime::sub() .

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

  • DateTimeImmutable
  • DateTimeImmutable::createFromFormat() — Разбирает строку с датой согласно указанному формату
  • Форматы даты и времени
  • checkdate() — Проверяет корректность даты по григорианскому календарю
  • strptime() — Разбирает строку даты/времени, сгенерированную функцией strftime

User Contributed Notes 4 notes

Be aware of this: 1 month before the 31st day, it will return the same month:

echo date ( ‘m’ , strtotime ( ‘2023-05-30 -1 month’ )) ; //returns 04
echo date ( ‘m’ , strtotime ( ‘2023-05-31 -1 month’ )) ; //returns 05, not 04
?>

So, don’t use this to operate on the month of the result.
A better way to know what month was the previous month would be:

//considering today is 2023-05-31.

$firstOfThisMonth = date ( ‘Y-m’ ) . ‘-01’ ; //returns 2023-05-01
echo date ( ‘m’ , strtotime ( $firstOfThisMonth . ‘ -1 month’ )) ; //returns 04
?>

Be careful when using two numbers as the year. I came across this situation:

echo strtotime ( ‘24.11.22’ );
echo date ( ‘d.m.Y H:i:s’ , 1669324282 ) . «\n\n» ;

// But
echo strtotime ( ‘24.11.2022’ );
echo date ( ‘d.m.Y H:i:s’ , 1669237200 );

This is the link to the relative formats that can be used in this function. It’s not easy to find in the documentation.

Here some examples:
$today = date ( ‘Y-m-d’ , strtotime ( ‘today’ ) );
echo «Today: » . $today ;

//Basic Example
$tomorrow = date ( ‘Y-m-d’ , strtotime ( ‘tomorrow’ ) );
echo «\n\nTomorrow: » . $tomorrow ;

$yesterday = date ( ‘Y-m-d’ , strtotime ( ‘yesterday’ ) );
echo «\n\nYesterday: » . $yesterday ;

// Add o subtract Month
$variable = date ( ‘Y-m-d’ , strtotime ( ‘+1 month’ ) );
echo «\n\nAdd one month: » . $variable ;

// Print: Add one month: 2023-07-01

$variable = date ( ‘Y-m-d’ , strtotime ( ‘-1 month’ ) );
echo «\n\nSubstract one month: » . $variable ;

// Print: Substract one month: 2023-05-01

// More complex formats:
// ERROR / BUG: If today is the last day of the month. This examples can be one error or bug.
// If you are looking el first day of previous or next month you dont must use last Relative Format.
// You must use ‘first day of 2 months ago’ or ‘first day of previous month’
// See you:
// https://bugs.php.net/bug.php?id=22486
// https://bugs.php.net/bug.php?id=44073
// strtotime(«+1 Month»)
// produces the wrong result on the 31st day of the month.
// on January 31, date(«m»,strtotime(«+1 Month»)) will return 03 instead of 02

// Another example:
$dt1 = strtotime ( «2023-01-30» );
$month = strtotime ( «+1 month» , $dt1 );
echo «\n\nToday is: » . date ( ‘Y-m-d’ , $dt1 );
echo «\nBUG add month: » . date ( «Y-m-d» , $month );

// Print:
// Today is: 2023-01-30
// BUG add month: 2023-03-02

$dt1 = strtotime ( «2023-02-28» );
$month = strtotime ( «-1 month» , $dt1 );
echo «\n\nToday is: » . date ( ‘Y-m-d’ , $dt1 );
echo «\nBUG substract month: » . date ( «Y-m-d» , $month );

// Print:
// Today is: 2023-02-28
// BUG substract month: 2023-01-28

$dt1 = strtotime ( «2023-01-30» );
$month = strtotime ( «first day of next month» , $dt1 );
echo «\n\nToday is: » . date ( ‘Y-m-d’ , $dt1 );
echo «\nFirst day of next month: » . date ( «Y-m-d» , $month );

// Print:
// Today is: 2023-01-30
// First day of next month: 2023-02-01

$dt1 = strtotime ( «2023-02-28» );
$month = strtotime ( «last day of last month» , $dt1 );
echo «\n\nToday is: » . date ( ‘Y-m-d’ , $dt1 );
echo «\nLast day of last month: » . date ( «Y-m-d» , $month );

// Print:
// Today is: 2023-02-28
// Last day of last month: 2023-01-31

$dt1 = strtotime ( «2023-02-28» );
$month = strtotime ( «first day of 2 months ago» , $dt1 );
echo «\n\nToday is: » . date ( ‘Y-m-d’ , $dt1 );
echo «\nFirst day of 2 months ago: » . date ( «Y-m-d» , $month );

// Print:
// Today is: 2023-02-28
// First day of 2 months ago: 2022-12-01

Note:
If day of month is 12 or less, or year is entered as a two digit number and less than 31 or 12 then you may get the wrong time value.
If you know the format used with the date string, then use the following code: (PHP version 5.5 or later)
[code]function getStrtotime($timeDateStr, $formatOfStr=»j/m/Y») // Same as strtotime() but using the format $formatOfStr.
// Works with PHP version 5.5 and later.
// On error reading the time string, returns a date that never existed. 3/09/1752 Julian/Gregorian calendar switch.
$timeStamp = DateTimeImmutable::createFromFormat($formatOfStr,$timeDateStr);
if($timeStamp===false) // Bad date string or format string.
return -6858133619; // 3/09/1752
> else // Date string and format ok.
return $timeStamp->format(«U»); // UNIX timestamp from 1/01/1970, 0:00:00 gmt
>
>

print date(«j/m/Y», getStrtotime(«1/02/2022», «j/m/Y»)).» Standard format. (j)\n»;
print date(«j/m/Y», getStrtotime(«1/02/2022», «d/m/Y»)).» Standard format. (d)\n»;
print date(«j/m/Y», getStrtotime(«1/02/2022», «j/m/y»)).» Standard format. (y) <— Bad date as 2022 is not two digits.\n»;
print date(«j/m/Y», getStrtotime(«21/02/2022», «j/m/Y»)).» Standard format. (j)\n»;
print date(«j/m/Y», getStrtotime(«21/02/2022», «d/m/Y»)).» Standard format. (d)\n»;
print date(«j/m/Y», getStrtotime(«2/01/2022», «m/j/Y»)).» US format.\n»;
print date(«j/m/Y», getStrtotime(«2-01-22», «m-j-y»)).» Two digit year, US format. (Y)\n»;
print date(«j/m/Y», getStrtotime(«2-01-22», «m-j-Y»)).» Two digit year, US format. (y) <— Wrong year if two digits.\n»;
print date(«j/m/Y», getStrtotime(«3/09/1752», «j/m/Y»)).» No such date.\n»;
print date(«j/m/Y», getStrtotime(«50/00/19999», «j/m/Y»)).» Bad date string.\n»;
print date(«j/m/Y», getStrtotime(«1-02-2022», «j/m/Y»)).» Wrong — or / used.\n»;
[/code]Output:
1/02/2022 Standard format. (j)
1/02/2022 Standard format. (d)
3/09/1752 Standard format. (y) 21/02/2022 Standard format. (j)
21/02/2022 Standard format. (d)
1/02/2022 US format.
1/02/2022 Two digit year, US format. (Y)
1/02/0022 Two digit year, US format. (y) 3/09/1752 No such date.
3/09/1752 Bad date string.
3/09/1752 Wrong — or / used.

  • Функции даты и времени
    • checkdate
    • date_​add
    • date_​create_​from_​format
    • date_​create_​immutable_​from_​format
    • date_​create_​immutable
    • date_​create
    • date_​date_​set
    • date_​default_​timezone_​get
    • date_​default_​timezone_​set
    • date_​diff
    • date_​format
    • date_​get_​last_​errors
    • date_​interval_​create_​from_​date_​string
    • date_​interval_​format
    • date_​isodate_​set
    • date_​modify
    • date_​offset_​get
    • date_​parse_​from_​format
    • date_​parse
    • date_​sub
    • date_​sun_​info
    • date_​sunrise
    • date_​sunset
    • date_​time_​set
    • date_​timestamp_​get
    • date_​timestamp_​set
    • date_​timezone_​get
    • date_​timezone_​set
    • date
    • getdate
    • gettimeofday
    • gmdate
    • gmmktime
    • gmstrftime
    • idate
    • localtime
    • microtime
    • mktime
    • strftime
    • strptime
    • strtotime
    • time
    • timezone_​abbreviations_​list
    • timezone_​identifiers_​list
    • timezone_​location_​get
    • timezone_​name_​from_​abbr
    • timezone_​name_​get
    • timezone_​offset_​get
    • timezone_​open
    • timezone_​transitions_​get
    • timezone_​version_​get

    Источник

Оцените статью