PHP 8.3.4 Released!

DateTime::createFromFormat

date_create_from_format

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

DateTime::createFromFormat -- date_create_from_format指定した書式で時刻文字列をパースする

説明

オブジェクト指向型

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

手続き型

新しい DateTime オブジェクトを返します。 このオブジェクトは、datetime で指定した文字列を format で指定した書式に沿って解釈した時刻を表します。

DateTimeImmutable::createFromFormat()date_create_immutable_from_format() と似ていますが、 DateTime オブジェクトを生成します。

このメソッドドキュメントは、パラメータや使用例、注意点も含めて DateTimeImmutable::createFromFormat のページにあります。

パラメータ

DateTimeImmutable::createFromFormat も参照ください。

戻り値

新しい DateTime のインスタンスを返します。失敗した場合に false を返します。

エラー / 例外

datetime に NULLバイトが含まれている場合は、 ValueError がスローされます。

変更履歴

バージョン 説明
8.0.21, 8.1.8, 8.2.0 datetime に NULLバイトが含まれている場合は、 ValueError がスローされるようになりました。 これより前のバージョンでは、こうした値は静かに無視されていました。

豊富な例が、DateTimeImmutable::createFromFormat のページにあるので参照ください。

参考

add a note

User Contributed Notes 2 notes

up
3
Steven De Volder
5 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