Php перевод даты unix

strtotime

Первым параметром функции должна быть строка с датой на английском языке, которая будет преобразована в метку времени относительно метки времени, переданной в now, или текущего времени, если аргумент now опущен. В случае ошибки возвращается -1.

Функция strtotime() использует GNU формат даты Date Input Formats, где описывается синтаксис аргумента time.

Проверить работу функции strtotime:

Функция strtotime() может распознавать следующие слова и сокращения.

  • Название месяцев: 12 месяцев и соответствующие сокращения: Январь — January, Февраль — February, Март — March, Апрель — April, Май — May, Июнь — June, Июль — July, Август — August, Сентябрь — September, Октябрь — October, Ноябрь — November, Декабрь — December.
  • Название дней недели: 7 дней и соответствующие сокращения:Понедельник — Monday, Вторник — Tuesday, Среда — Wednesday, Четверг — Thursday, Пятница — Friday, Суббота — Saturday, Воскресенье — Sunday.
  • Название единиц времени: year (год), month (месяц), fortnight (две недели), week (неделя), day (день), hour (час), minute (минута), second (секунда), am (до полудня), рт (после полудня).
  • Некоторые английские слова: ago (тому назад), now (сейчас), last (длиться), next (следующий); this (этот), tomorrow (завтра), yesterday (вчера).
  • Знаки «плюс» и «минус».
  • Все числа.
  • Временные зоны: например, gmt (Greenwich Mean Time — среднее время по Гринвичу) или pdt (Pacific Daylight Time — дневное тихоокеанское время).
Пример 1. Пример использования функции strtotime()
echo strtotime("now"); echo strtotime("22.01.1971 10:11:36"); echo strtotime("10 September 2000"); echo strtotime("+1 day"); echo strtotime("+1 week"); echo strtotime("+1 week 2 days 4 hours 2 seconds"); echo strtotime("next Thursday"); echo strtotime("last Monday"); echo strtotime('Monday this week'); echo strtotime('first day'); echo strtotime('last day next month'); echo strtotime('last day last month'); echo strtotime('2009-12 last day'); // это не сработает, если в обратном порядке год и месяц echo strtotime('2009-03 last day'); echo strtotime('2009-03'); echo strtotime('last day of march 2009'); echo strtotime('last day of march'); echo strtotime('yesterday 14:00'); echo date("d.m.Y",strtotime("first day of previous month")); // первый день прошлого месяца echo date("d.m.Y",strtotime("last day of previous month")); // последний день прошлого месяца echo date("d.m.Y",strtotime("first day of this month")); // первый день текущего месяца echo date("d.m.Y",strtotime("first day of next month")); // первый день следующего месяца echo date('Y-m-d h:i:s',strtotime("-18 hours")); echo strtotime("tomorrow"); # 24 часа от сегодня echo strtotime("now + 24 hours"); echo strtotime("last Saturday"); echo strtotime("8pm + 3 days"); echo strtotime("2 weeks ago"); # две недели назад echo strtotime("next year gmt"); # на один год вперед echo strtotime ("tomorrow 4am"), echo strtotime( date("Y-01-01") ); // начало года echo strtotime( "next day 00:00" ); // начало следующего дня
Пример 2. Проверка ошибок
$str = 'Not Good'; if (($timestamp = strtotime($str)) === -1) < echo "Строка ($str) недопустима"; >else

Замечание: Для большинства систем допустимыми являются даты с 13 декабря 1901, 20:45:54 GMT по 19 января 2038, 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битового целого со знаком). Для Windows допустимы даты с 01-01-1970 по 19-01-2038. Не все платформы поддерживают отрицательные метки времени, поэтому даты ранее 1 января 1970 г. не поддерживаются в Windows, некоторых версиях Linux и некоторых других операционных системах.

Читайте также:  Java file class url

Замечание: GMT формат с помощью strtotime преобразуется некорректно:

$strtotime = strtotime("Tue, 21 May 2013 09:10:30 GMT"); echo date("Y-m-d H:i:s", $strtotime),PHP_EOL; $strtotime = DateTime::createFromFormat("D, d M Y g:i:s O", "Tue, 21 May 2013 09:10:30 GMT"); echo $strtotime->format("Y-m-d H:i:s");

Источник

strtotime

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

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

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

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

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

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

Возвращает временную метку в случае успеха, иначе возвращается FALSE . До версии PHP 5.1.0 в случае ошибки эта функция возвращала -1.

Ошибки

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

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

Теперь ошибки, связанные с временными зонами, генерируют ошибки уровня E_STRICT и E_NOTICE .

Примеры

Пример #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 Проверка ошибок

// до версии PHP 5.1.0 вместо false необходимо было сравнивать со значением -1
if (( $timestamp = strtotime ( $str )) === false ) echo «Строка ( $str ) недопустима» ;
> else echo » $str == » . date ( ‘l dS \o\f F Y h:i:s A’ , $timestamp );
>
?>

Примечания

Замечание:

Если количество лет указано двумя цифрами, то значения 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-битового знакового целого).

До версии PHP 5.1.0, не все платформы поддерживают отрицательные метки времени, поэтому поддерживаемый диапазон дат может быть ограничен Эпохой Unix. Это означает, что даты ранее 1 января 1970 г. не будут работать в Windows, некоторых дистрибутивах Linux и нескольких других операционных системах.

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

Замечание:

Даты в формате m/d/y или d-m-y разрешают неоднозначность с помощью анализа разделителей их элементов: если разделителем является слеш (/), то дата интерпретируется в американском формате m/d/y, если же разделителем является дефис () или точка (.), то подразумевается использование европейского форматаd-m-y.

Чтобы избежать потенциальной неоднозначности, рекомендуется использовать даты в формате стандарта ISO 8601 (YYYY-MM-DD) либо пользоваться функцией DateTime::createFromFormat() там, где это возможно.

Замечание:

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

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

  • Форматы даты и времени
  • DateTime::createFromFormat() — Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату
  • checkdate() — Проверяет корректность даты по григорианскому календарю
  • strptime() — Разбирает строку даты/времени сгенерированную функцией strftime
Читайте также:  Php при подключении через include

Источник

How to convert datetime in PHP to a Unix timestamp

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

Overview

While working with the MySQL database in PHP, we may need to record the time instance at which an event occurs. This instance can be stored as a table record. We can the instance as a table record by using the datetime or timestamp MySQL data types. The problem associated with this procedure is that it cannot display the date in a very human-friendly and easily-readable format.

We get the following from the datetime and timestamp MySQL table columns:

But we may want to display the date in the format shown in the image below:

This shot teaches us how to display a date in this format, as a PHP script.

Before we learn to display the date in the aforementioned format, let’s look at the problems associated with MySQL table timestamp columns.

Problems

  • The datetime from the table is a string.
  • It comes from the database table column of type timestamp , which usually presents datetime in the format 2021-11-17 13:02:18 .
  • This format is not a Unix timestamp. We’ll need to convert the format to a Unix timestamp in order to get the date in the format shown in image above.

Converting datetime strings to a Unix timestamp

A combination of two PHP functions, the strtotime() and the date() functions, will produce an output like the one shown in the image above.

  • The strtotime() function converts any given date string into a Unix timestamp. It only accepts the date string as a parameter.
  • The date() function outputs the current time, or the time relative to the provided timestamp (if any), in the specified format. It takes the format we wish to display the date in and the optional timestamp as its two parameters.
Читайте также:  Node js javascript runtime adobe

Now, we will delve into some code examples.

The incorrect approach

The code below is an incorrect way of trying to get the output we’ve shown above, which may be our first approach while trying out solutions to that problem for the first time.

The output is not what we want, and that is because we didn’t convert the timestamp into a proper Unix timestamp before passing it to the date() function.

$mytimestamp = '2021-11-17 13:02:18';
// $dating = intval($mytimestamp);
// echo $dating;
$converted = date('m d, Y',$mytimestamp);
echo $converted;
?>

of a specific value fetched from the database in the provided code,##

The correct approach

In this second code, we use the strtotime() function to convert the datetime string from a database table into a Unix timestamp. Then, with the help of the date() function, we set the timestamp to various date formats of our choice.

What is the Unix timestamp?

This is the number of seconds since the Unix epoch time (01-01-1970) .

For more tips on the PHP date() function, we can see this post.

Note: The escape character is used in the code snippet below to escape the words that are just used as text, so that they are not given special interpretation by the function.

Code explanation

In the code below, a datetime string, saved in the variable $d , is converted to a Unix timestamp with the strtotime() function. It is then saved to the variable $ad on line 5.

Note: To use the current date and time instead of a specific value fetched from the database in the provided code, comment out $d = ‘2021-11-17 13:02:18’; with // and uncomment $d = date(‘Y-m-d H:i:s’); in the provided code, it will assign the current datetime to the variable $d .

Источник

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