Convert time with php

PHP Epoch Converter and Date/Time Routines

How to convert epoch / UNIX timestamps to normal readable date/time using PHP 7.

Getting current epoch time in PHP

Time returns an integer with the current epoch:

time() // current Unix timestamp microtime(true) // microtime returns timestamp with microseconds (param: true=float, false=string) 

Convert from epoch to human-readable date in PHP

1. Use the ‘date’ function.

$epoch = 1483228800; echo date('r', $epoch); // output as RFC 2822 date - returns local time echo gmdate('r', $epoch); // returns GMT/UTC time: Sun, 01 Jan 2017 00:00:00 +0000 

You can use the time zone code below (date_default_timezone_set) to switch the time zone of the input date.

2. Use the DateTime class.

$epoch = 1483228800; $dt = new DateTime("@$epoch"); // convert UNIX timestamp to PHP DateTime echo $dt->format('Y-m-d H:i:s'); // output = 2017-01-01 00:00:00 

In the examples above «r» and «Y-m-d H:i:s» are PHP date formats, other examples:

Format Output
r Wed, 15 Mar 2017 12:00:00 +0100 (RFC 2822 date)
c 2017-03-15T12:00:00+01:00 (ISO 8601 date)
M/d/Y Mar/15/2017
d-m-Y 15-03-2017
Y-m-d H:i:s 2017-03-15 12:00:00
Читайте также:  Свойства элементов форм html

Convert from human-readable date to epoch in PHP

strtotime parses most English language date texts to epoch/Unix Time.

echo strtotime("15 November 2017"); // . or . echo strtotime("2017/11/15"); // . or . echo strtotime("+10 days"); // 10 days from now 
if ((strtotime("this is no date")) === false)

2. Using the DateTime class:

The PHP DateTime class is nicer to use:

// object oriented $date = new DateTime('01/15/2017'); // format: MM/DD/YYYY echo $date->format('U'); // or procedural $date = date_create('01/15/2017'); echo date_format($date, 'U'); 

The date format ‘U’ converts the date to a UNIX timestamp.

This version is more of a hassle but works on any PHP version.

// PHP 5.1+ date_default_timezone_set('UTC'); // optional mktime ( $hour, $minute, $second, $month, $day, $year ); // example: generate epoch for Jan 1, 2000 (all PHP versions) echo mktime(0, 0, 0, 1, 1, 2000); 

All these PHP routines can’t handle dates before 13 December 1901.

Set your timezone

Use date_default_timezone_set to set/overrule your timezone.
The PHP time zone handling takes care of daylight saving times (list of available time zones).

date_default_timezone_set('Europe/Amsterdam'); date_default_timezone_set('America/New York'); date_default_timezone_set('EST'); date_default_timezone_set('UTC'); 

Convert date/time to another time zone

$TimeStr="2017-01-01 12:00:00"; $TimeZoneNameFrom="UTC"; $TimeZoneNameTo="Europe/Amsterdam"; echo date_create($TimeStr, new DateTimeZone($TimeZoneNameFrom)) ->setTimezone(new DateTimeZone($TimeZoneNameTo))->format("Y-m-d H:i:s"); 

Adding or subtracting years/months to a date

With strtotime you can easily add or subtract years/months/days/hours/minutes/seconds to a date.

$currentDate = time(); // get current date echo "It is now: ".date("Y-m-d H:i:s", $currentDate)."\n "; $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 year"); // add 1 year to current date echo "Date in epoch: ".$date."\n "; echo "Readable date: ".date("Y-m-d H:i:s",$date)."\n "; 
$date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 month"); // add 1 month to a date $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +6 months"); // add 6 months $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " +1 day"); // add 1 day $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " -12 hours"); // subtract 12 hours $date = strtotime(date("Y-m-d H:i:s", $currentDate) . " -1 day -12 hours"); // subtract 1 day and 12 hours 

Источник

Converting a PHP timestamp to a date(time)

In this PHP tutorial, we’re going to convert a timestamp in PHP to a date (optionally with time) using custom formatting. We’ll start by getting the current time stamp and display it using the simple date function. Next, we’ll use the current timestamp to create a Date Time object, format the date and display it. We’ll then view some of the date and time formatting options, followed by the Date Time Zone class. And finally, we’ll create a function to convert a timestamp to DateTime with time zone and date format parameters.

In this article

Getting a Timestamp

Let’s start with a basic PHP function to get the timestamp, we’ll use time() to get the current timestamp and date to format the output.

The time stamp saved in $now is similar to 1610246191, so we format it using date(‘Y-m-d’, $now) for a user friendly output. The timestamp returned is in seconds, see the microtime function to get a timestamp including micro seconds.

Timestamp To Date Time Object

While we can use the date function to format our date or timestamp, it isn’t the object oriented way of doing it. Let’s create a DateTime object and set the timestamp.

We can then output the date and time using the format method with the ‘c’ datetime parameter.

Formatting a Date

The format method can format a date in many different ways, common formats are: Y-m-d and d/m/Y .

The PHP manual has many more date formats available.

Formatting a Time

The DateTime class can also format the same timestamp in time only format.

We use the H:i:s(Hour, Minute, Second) format in the code above.

Date with TimeZone

The DateTime object can be set to use a specific time zone. We create a new DateTimeZone with a particular time zone and call the setTimeZone method on our DateTime object.

The DateTimeZone class has many timezone options. The PHP code example above displays the same timestamp using different time zones.

Converting a Timestamp to Date Time

Our final function is a combination of DateTime and DateTimeZone with 3 parameters: a timestamp, time zone and date/time format with default formatting.

Our custom PHP function timeStampToDateTime takes a timestamp as first parameter, which could be the current timestamp or any other time stamp (maybe a timestamp from a db). It uses the timezone and format to return a human readable date time string.

Key Takeaways

  • We can use the time() function to get the current timestamp and the date function to format a timestamp.
  • The DateTime class is the object oriented way of working with dates and times.
  • The DateTimeZone class provides time zone functionality which can be used with the DateTime class to work with dates and times.
  • The format , setTimeZone and setTimeStamp methods are the primary methods we can use to convert a timestamp to date/time.
  • Related PHP functions: microtime

This is the footer. If you’re reading this, it means you’ve reached the bottom of the page.
It would also imply that you’re interested in PHP, in which case, you’re in the right place.
We’d love to know what you think, so please do check back in a few days and hopefully the feedback form will be ready.

Источник

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

Источник

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