DateTimeImmutable::__construct
date_create_immutable
(PHP 5 >= 5.5.0)
DateTimeImmutable::__construct -- date_create_immutable — Возвращает новый объект DateTimeImmutable
Описание
Объектно-ориентированный стиль
Процедурный стиль
DateTimeImmutable date_create_immutable
([ string
$time
= "now"
[, DateTimeZone $timezone
= NULL
]] )Данный конструктор похож на DateTime::__construct(), но работает с DateTimeImmutable.
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с датой и временем
- Дата и Время
- Функция DateTimeImmutable::add() - Добавляет указанное количество дней, месяцев, лет, часов, минут и секунд.
- Функция DateTimeImmutable::__construct() - Возвращает новый объект DateTimeImmutable
- Функция DateTimeImmutable::createFromFormat() - Возвращает новый объект DateTimeImmutable, отформатированный согласно переданному формату
- DateTimeImmutable::createFromMutable
- Функция DateTimeImmutable::getLastErrors() - Возвращает предупреждения и ошибки
- Функция DateTimeImmutable::modify() - Изменяет временную метку
- Функция DateTimeImmutable::__set_state() - Обработчик __set_state
- Функция DateTimeImmutable::setDate() - Устанавливает дату
- Функция DateTimeImmutable::setISODate() - Устанавливает дату в формате ISO
- Функция DateTimeImmutable::setTime() - Устанавливает время
- Функция DateTimeImmutable::setTimestamp() - Устанавливает дату и время по переданной временной метке Unix
- Функция DateTimeImmutable::setTimezone() - Устанавливает временную зону
- Функция DateTimeImmutable::sub() - Вычитает переданное количество дней, месяцев, лет, часов, минут и секунд
Коментарии
"If $timezone is omitted or null, the current timezone will be used." - note, that timezone IS NOT equal offset, if its important for your application.
If default timezone = Europe/Moscow, then:
echo (new \DateTimeImmutable('2014-10'))->format(DATE_ATOM); // gives "2014-10-01T00:00:00+04:00"
echo (new \DateTimeImmutable('2014-11'))->format(DATE_ATOM); // gives "2014-11-01T00:00:00+03:00"
because of law changes (abolition of "summer time").
Working on a (REST) interface between JavaScript and a database needs to take care of the problem of the time zone info. In JavaScript JSON.stringify() will convert all dates to UTC. Makes sense. If we receive and decode this on in the PHP realm we should explicitly say so and altought null indicates the configured locale timezone although I do believe that more often than not no timezone is configured in PHP. So better be save than sorry and prevent you to miss your flight:
<?php
$jsonString = '{ "date": "2025-05-04T11:58:37.848Z" }';
$dateString = json_decode($jsonString, true)['date']; // will contain the date in UTC (Zulu) tz
$d = new \DateTimeImmutable($dateString, new \DateTimeZone('UTC')); // interpreted as such
$databaseZone = new \DateTimeZone("Europe/Zurich");
$d = $d->setTimeZone( $databaseZone ); // but our server is somewhere else
var_dump($d);
// Now we can store the date in our local database, which is blissfully unaware of timezones
?>