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

过程化风格

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

返回新的 DateTime 对象,该对象是通过指定 format 将表示日期和时间的 datetime 格式化生成。

类似于 DateTimeImmutable::createFromFormat()date_create_immutable_from_format(),但创建的是 DateTime 对象。

此方法(包括参数、示例和注意事项)记录在 DateTimeImmutable::createFromFormat 页面上。

返回值

返回 DateTime 对象 或者在失败时返回 false

错误/异常

datetime 包含 NULL 字节时,此方法抛出 ValueError

更新日志

版本 说明
8.0.21、8.1.8、8.2.0 现在,当将 NULL 字节传递到 datetime 时,会引发 ValueError,而之前会默默忽略该错误。

示例

有关大量示例,请参阅 DateTimeImmutable::createFromFormat

参见

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