- PHP DateTime
- Introduction to the PHP DateTime class
- Creating a DateTime object from a string
- Comparing two DateTime objects
- Calculating the differences between two DateTime objects
- Adding an interval to a DateTime object
- Summary
- date_create
- Список параметров
- Возвращаемые значения
- Ошибки
- Список изменений
- Примеры
- Смотрите также
- timezone_open
- Список параметров
- Возвращаемые значения
- Ошибки
- Примеры
PHP DateTime
Summary: in this tutorial, you’ll learn how to work with the date and time in an object-oriented way.
Introduction to the PHP DateTime class
PHP provides a set of date and time classes that allow you to work with the date and time in an object-oriented way.
To create a new date and time object, you use the DateTime class. For example:
$datetime = new DateTime(); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-15 06:30:40.294788" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" >
Code language: PHP (php)
The DateTime object represents the current date and time in the timezone specified in the PHP configuration file ( php.ini )
To set a new timezone, you create a new DateTimeZone object and pass it to the setTimezone() method of the DateTime object:
$datetime = new DateTime(); $timezone = new DateTimeZone('America/Los_Angeles'); $datetime->setTimezone($timezone); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-14 21:33:27.986925" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "America/Los_Angeles" >
Code language: PHP (php)
In this example, we create a new DateTimeZone object and set it to «America/Los_Angeles» . To get valid timezones supported by PHP, check out the timezone list.
To format a DateTime object, you use the format() method. The format string parameters are the same as those you use for the date() function. For example:
$datetime = new DateTime(); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
07/15/2021 6:38 AM
Code language: PHP (php)
To set a specific date and time, you can pass a date & time string to the DateTime() constructor like this:
$datetime = new DateTime('12/31/2019 12:00 PM'); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Or you can use the setDate() function to set a date:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 6:42 AM
Code language: PHP (php)
The time is derived from the current time. To set the time, you use the setTime() function:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); $datetime->setTime(5, 30, 0); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 5:30 AM
Code language: PHP (php)
Since the setDate() , setTime() , and setTimeZone() method returns the DateTime object, you can chain them like this which is quite convenient.
$datetime = new DateTime(); echo $datetime->setDate(2020, 5, 1) ->setTime(5, 30) ->setTimezone(new DateTimeZone('America/New_York')) ->format('m/d/Y g:i A');
Code language: PHP (php)
04/30/2020 11:30 PM
Code language: PHP (php)
Creating a DateTime object from a string
When you pass the date string ’06/08/2021′ to the DateTime() constructor or setDate() function, PHP interprets it as m/d/Y . For example:
$datetime = new DateTime('06/08/2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
June 8th, 2021
Code language: PHP (php)
If you want to pass it as August 6th, 2021, you need to use the – or . instead of /. For example:
$datetime = new DateTime('06-08-2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
However, if you want to parse the date string ’06/08/2021′ as d/m/Y, you need to replace the / with – or . manually:
$ds = '06/08/2021'; $datetime = new DateTime(str_replace('/', '-', $ds)); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
A better way to do it is to use the createFromFormat() static method of the DateTime object:
$ds = '06/08/2021'; $datetime = DateTime::createFromFormat('d/m/Y', $ds); echo $datetime->format('F jS, Y');
Code language: PHP (php)
In this example, we pass the date format as the first argument and the date string as the second argument.
Note that when you pass a date string without the time, the DateTime() constructor uses midnight time. However, the createFromFormat() method uses the current time.
Comparing two DateTime objects
PHP allows you to compare two DateTime objects using the comparison operators including >, >=, . For example:
$datetime1 = new DateTime('01/01/2021 10:00 AM'); $datetime2 = new DateTime('01/01/2021 09:00 AM'); var_dump($datetime1 < $datetime2); // false var_dump($datetime1 > $datetime2); // true var_dump($datetime1 == $datetime2); // false var_dump($datetime1 $datetime2); // 1
Code language: PHP (php)
Calculating the differences between two DateTime objects
The diff() method of the DateTime() object returns the difference between two DateTime() objects as a DateInterval object. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); $age = $to_date->diff($dob); var_dump($age);
Code language: PHP (php)
object(DateInterval)#3 (16) ["y"]=> int(31) ["m"]=> int(6) ["d"]=> int(14) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(11518) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) >
Code language: PHP (php)
The DateInterval represents the differences between two dates in the year, month, day, hour, etc. To format the difference, you use the DateInterval ‘s format. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); echo $to_date->diff($dob)->format('%Y years, %m months, %d days');
Code language: PHP (php)
31 years, 6 months, 14 days
Code language: PHP (php)
Adding an interval to a DateTime object
To add an interval to date, you create a new DateInterval object and pass it to the add() method. The following example adds 1 year 2 months to the date 01/01/2021 :
$datetime = new DateTime('01/01/2021'); $datetime->add(new DateInterval('P1Y2M')); echo $datetime->format('m/d/Y');
Code language: PHP (php)
03/01/2022
Code language: PHP (php)
To format a date interval, you use the date interval format strings.
To subtract an interval from a DateTime object, you create a negative interval and use the add() method.
Summary
- Use the DateTime class to work with the date and time.
- Use the DateTimeZone class to work with time zones.
- Use the comparison operators to compare two DateTime objects.
- Use the diff() method to calculate the difference between to DateTime objects.
- Use the DateInterval class to represent a date and time interval.
- Use the add() method to add an interval to or subtract an interval from a DateTime object.
date_create
Создает и возвращает новый экземпляр класса DateTime.
Список параметров
Строка даты/времени. Объяснение корректных форматов дано в Форматы даты и времени.
Если используется аргумент $timezone , то для получения текущего времени в новом объекте достаточно передать NULL в качестве этого аргумента.
Объект класса DateTimeZone представляющий временную зону параметра $time .
Если аргумент $timezone не задан, будет использована текущая временная зона.
Замечание:
Значение аргумента $timezone равно как и текущая временная зона не будут учитываться, если в качестве аргумента $time передается метка времени UNIX (например @946684800) или время, в котором временная зона уже содержится (например 2010-01-28T15:00:00+02:00).
Возвращаемые значения
Возвращает созданный объект класса DateTime. Процедурный стиль возвращает FALSE в случае возникновения ошибки.
Ошибки
В случае ошибки выбрасывает исключение Exception.
Список изменений
Версия | Описание |
---|---|
5.3.0 | В случае задания параметру time неверного формата даты/времени выбрасывается исключение. Раньше скрипт выдавал ошибку. |
Примеры
Пример #1 Пример использования DateTime::__construct()
try $date = new DateTime ( ‘2000-01-01’ );
> catch ( Exception $e ) echo $e -> getMessage ();
exit( 1 );
>
?php
$date = date_create ( ‘2000-01-01’ );
if (! $date ) $e = date_get_last_errors ();
foreach ( $e [ ‘errors’ ] as $error ) echo » $error \n» ;
>
exit( 1 );
>
?php
echo date_format ( $date , ‘Y-m-d’ );
?>
Результат выполнения данных примеров:
Пример #2 Хитрости при использовании DateTime::__construct()
// Дата/время во временной зоне Вашего компьютера.
$date = new DateTime ( ‘2000-01-01’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?php
// Дата/время в заданной временной зоне.
$date = new DateTime ( ‘2000-01-01’ , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Текущие дата и время во временной зоне Вашего компьютера.
$date = new DateTime ();
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Текущие дата и время в заданной временной зоне.
$date = new DateTime ( null , new DateTimeZone ( ‘Pacific/Nauru’ ));
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Использование метки времени UNIX.
// Обратите внимание: результат во временной зоне UTC.
$date = new DateTime ( ‘@946684800’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
// Несуществующие значения все равно обрабатываются.
$date = new DateTime ( ‘2000-02-30’ );
echo $date -> format ( ‘Y-m-d H:i:sP’ ) . «\n» ;
?>
Результатом выполнения данного примера будет что-то подобное:
2000-01-01 00:00:00-05:00 2000-01-01 00:00:00+12:00 2010-04-24 10:24:16-04:00 2010-04-25 02:24:16+12:00 2000-01-01 00:00:00+00:00 2000-03-01 00:00:00-05:00
Смотрите также
- DateTime::createFromFormat() — Создает и возвращает экземпляр класса DateTime, соответствующий заданному формату
- DateTimeZone::__construct() — Создает новый объект DateTimeZone
- Форматы даты и времени
- date.timezone ini настройка
- date_default_timezone_set() — Устанавливает временную зону по умолчанию для всех функций даты/времени в скрипте
- DateTime::getLastErrors() — Возвращает предупреждения и ошибки
- checkdate() — Проверяет корректность даты по григорианскому календарю
timezone_open
Объект DateTimeZone предоставляет доступ к трём различным типам правил временных зон: Смещение UTC (тип 1 ), сокращение часового пояса (тип 2 ) и идентификаторы часовых поясов, опубликованные в базе данных часовых поясов IANA (тип 3 ).
Объект DateTimeZone может быть присоединён к объектам DateTime и DateTimeImmutable , чтобы иметь возможность отображать часовой пояс, заключённый в этих объектах в локальном часовом поясе.
Список параметров
Одно из поддерживаемых имён часовых поясов или значение смещения (+0200) или аббревиатура часового пояса (BST).
Возвращаемые значения
В случае успешного выполнения возвращает DateTimeZone . Процедурный стиль возвращает false в случае возникновения ошибки.
Ошибки
Метод выбрасывает исключение Exception , если указанный часовой пояс не распознан как допустимый.
Примеры
Пример #1 Создание и присоединение DateTimeZone к DateTimeImmutable
$d = new DateTimeImmutable ( «2022-06-02 15:44:48 UTC» );
?php
$timezones = [ ‘Europe/London’ , ‘GMT+04:45’ , ‘-06:00’ , ‘CEST’ ];
foreach ( $timezones as $tz ) $tzo = new DateTimeZone ( $tz );
$local = $d -> setTimezone ( $tzo );
echo $local -> format ( DateTimeInterface :: RFC2822 . ‘ — e’ ), «\n» ;
>
?>
Результат выполнения данного примера:
Thu, 02 Jun 2022 16:44:48 +0100 — Europe/London
Thu, 02 Jun 2022 20:29:48 +0445 — +04:45
Thu, 02 Jun 2022 09:44:48 -0600 — -06:00
Thu, 02 Jun 2022 17:44:48 +0200 — CEST
Пример #2 Перехват ошибок при создании экземпляра DateTimeZone
// Обработка ошибок с помощью перехвата исключений
$timezones = array( ‘Europe/London’ , ‘Mars/Phobos’ , ‘Jupiter/Europa’ );
?php
foreach ( $timezones as $tz ) try $mars = new DateTimeZone ( $tz );
> catch( Exception $e ) echo $e -> getMessage () . ‘
‘ ;
>
>
?>
Результат выполнения данного примера:
DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Mars/Phobos) DateTimeZone::__construct() [datetimezone.--construct]: Unknown or bad timezone (Jupiter/Europa)