(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DateTime::createFromFormat -- date_create_from_format — Analiza una cadena con un instante según un formato especificado
Estilo orientado a objetos
$format, string $datetime, ? DateTimeZone $timezone = null ): DateTime |false Estilo procedimental
$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.
Devuelve una nueva instancia de DateTime o false si ocurre un error.
Este método lanza ValueError cuando
datetime contiene bytes nulos (NULL-bytes).
| 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.
|
Para una lista extensa de ejemplos, vea DateTimeImmutable::createFromFormat.
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");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");