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_formatInterpreta um string de data/hora de acordo com um formato especificado.

Descrição

Estilo orientado a objetos

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

Estilo procedural

Retorna um novo objeto DateTime representando a data e a hora especificadas pelo string datetime, que foi formatado de acordo com o parâmetro format fornecido.

Equivalente a DateTimeImmutable::createFromFormat() e date_create_immutable_from_format(), respectivamente, mas cria um objeto DateTime.

Este método, incluindo parâmetros, exemplos e considerações estão documentados na página DateTimeImmutable::createFromFormat.

Valor Retornado

Retorna uma nova instância de DateTime ou false em caso de falha.

Erros/Exceções

Este método dispara uma exceção ValueError quando o parâmetro datetime contém bytes nulos.

Registro de Alterações

Versão Descrição
8.0.21, 8.1.8, 8.2.0 Agora dispara ValueError quando bytes nulos são passados pelo parâmetro datetime, o que antes era silencioamente ignorado.

Exemplos

Para um conjunto extenso de exemplos, veja DateTimeImmutable::createFromFormat.

Veja Também

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