DateTime::createFromFormat

date_create_from_format

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

DateTime::createFromFormat -- date_create_from_formatParses a time string according to a specified format

Descrizione

Stile orientato agli oggetti

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

Stile procedurale

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

Returns a new DateTime object representing the date and time specified by the datetime string, which was formatted in the given format.

Like DateTimeImmutable::createFromFormat() and date_create_immutable_from_format(), respectively, but creates a DateTime object.

This method, including parameters, examples, and considerations are documented on the DateTimeImmutable::createFromFormat page.

Elenco dei parametri

See DateTimeImmutable::createFromFormat.

Valori restituiti

Returns a new DateTime instance o false in caso di fallimento.

Errori/Eccezioni

This method throws ValueError when the datetime contains NULL-bytes.

Log delle modifiche

Versione Descrizione
8.0.21, 8.1.8, 8.2.0 Now throws ValueError when NULL-bytes are passed into datetime, which previously was silently ignored.

Esempi

For an extensive set of examples, see DateTimeImmutable::createFromFormat.

Vedere anche:

add a note add a note

User Contributed Notes 2 notes

up
3
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
1
mariani dot v at sfeir dot com
10 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