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_formatWertet eine Zeitangabe gemäß dem angegebenen Format aus

Beschreibung

Objektorientierter Stil

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

Prozeduraler Stil

Gibt ein neues DateTime-Objekt zurück. Es stellt das Datum und die Uhrzeit dar, die in der Zeichenkette datetime angegeben sind und gemäß dem angegebenen format formatiert wurden.

Wie DateTimeImmutable::createFromFormat() bzw. date_create_immutable_from_format(), erzeugt aber ein DateTime-Objekt.

Diese Methode ist einschließlich Parametern, Beispielen und Überlegungen auf der Seite DateTimeImmutable::createFromFormat dokumentiert.

Parameter-Liste

Siehe DateTimeImmutable::createFromFormat.

Rückgabewerte

Gibt eine neue DateTime-Instanz zurück. Bei einem Fehler wird false zurückgegeben.

Fehler/Exceptions

Wenn der Parameter datetime NULL-Bytes enthält, wirft diese Methode einen ValueError.

Changelog

Version Beschreibung
8.0.21, 8.1.8, 8.2.0 Wenn in datetime NULL-Bytes übergeben werden, wird nun ein ValueError geworfen; vorher wurde dies stillschweigend ignoriert.

Beispiele

Eine umfangreiche Sammlung von Beispielen ist unter DateTimeImmutable::createFromFormat zu finden.

Siehe auch

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