DateTime::createFromFormat

date_create_from_format

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

DateTime::createFromFormat -- date_create_from_format Разбирает строку времени по заданному формату

Описание

Объектно-ориентированный стиль

public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

Процедурный стиль

Метод возвращает новый объект DateTime, который представляет строку даты и времени datetime в формате format.

Метод работает аналогично методу DateTimeImmutable::createFromFormat() и функции date_create_immutable_from_format(), но создаёт объект DateTime.

Этот метод, включая параметры, примеры и рекомендации, описывает страница метода DateTimeImmutable::createFromFormat.

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

Смотрите параметры и их описание на странице метода DateTimeImmutable::createFromFormat.

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

Метод возвращает новый экземпляр класса DateTime или false, если возникла ошибка.

Ошибки

Метод выбрасывает исключение ValueError, если параметр datetime содержит NULL-байты.

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

Версия Описание
8.0.21, 8.1.8, 8.2.0 Теперь метод выбрасывает исключение ValueError, если в параметр datetime передали NULL-байты, что раньше метод без предупреждения игнорировал.

Примеры

Подробный набор примеров смотрите на странице метода DateTimeImmutable::createFromFormat.

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

Добавить

Примечания пользователей 2 notes

up
7
Steven De Volder
1 year ago
In the following code:$t = microtime(true);$now = DateTime::createFromFormat('U.u', $t);$now = $now->format("H:i:s.v");Trying to format() will return a fatal error if microtime(true) just so happened to return a float with all zeros as decimals. This is because DateTime::createFromFormat('U.u', $aFloatWithAllZeros) returns false.Workaround (the while loop is for testing if the solution works):$t = microtime(true);$now = DateTime::createFromFormat('U.u', $t);while (!is_bool($now)) {//for testing solution    $t = microtime(true);    $now = DateTime::createFromFormat('U.u', $t);}if (is_bool($now)) {//the problem    $now = DateTime::createFromFormat('U', $t);//the solution}$now = $now->format("H:i:s.v");
up
-3
mariani dot v at sfeir dot com
1 year ago
An easiest way to avoid error when microtime returns a non decimal float is to cast its result as a float using sprintf : $t = microtime(true);$now = DateTime::createFromFormat('U.u', sprintf('%f', $t));$now = $now->format("H:i:s.v");
To Top