LonghornPHP 2026

DateTime::createFromFormat

date_create_from_format

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

DateTime::createFromFormat -- date_create_from_formatAnaliza una cadena con un instante según un formato especificado

Descripción

Estilo orientado a objetos

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

Estilo procedimental

function date_create_from_format (string $format, string $datetime, ? DateTimeZone $timezone = null ): DateTime |false

Devuelve un nuevo objeto DateTime que representa la fecha y la hora especificadas por la cadena time, la cual fue formateada en el formato indicado en format.

Igual que DateTimeImmutable::createFromFormat() y date_create_immutable_from_format() , respectivamente, pero crea un objeto DateTime .

Este método, incluyendo parámetros, ejemplos y consideraciones están documentados en la página DateTimeImmutable::createFromFormat.

Valores devueltos

Devuelve una nueva instancia de DateTime o false si ocurre un error.

Errores/Excepciones

Este método lanza ValueError cuando datetime contiene bytes nulos (NULL-bytes).

Historial de cambios

Versión Descripción
8.0.21, 8.1.8, 8.2.0 Ahora lanza ValueError cuando se pasan bytes nulos (NULL-bytes) a datetime, cuando antes eran ignorados silenciosamente.

Ejemplos

Para una lista extensa de ejemplos, vea DateTimeImmutable::createFromFormat.

Véase también

Found A Problem?

Learn How To Improve This PageSubmit a Pull RequestReport a Bug
+add a note

User Contributed Notes 2 notes

up
7
Steven De Volder
2 years 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
-4
mariani dot v at sfeir dot com
2 years 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");
+add a note

AltStyle によって変換されたページ (->オリジナル) /