CakeFest 2024: The Official CakePHP Conference

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 содержит нулевые байты.

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

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

Примеры

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

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

add a note

User Contributed Notes 2 notes

up
3
Steven De Volder
6 months 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
1
mariani dot v at sfeir dot com
2 months 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