PHP Conference Japan 2024

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

程序風格 (Procedural style)

返回一個新的 DateTime 物件,表示由 datetime 字串指定的日期和時間,該字串以指定的 format 格式化。

分別類似於 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

另請參閱

新增註釋

使用者貢獻的註釋 2 則註釋

Steven De Volder
1 年前
在以下程式碼中
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
$now = $now->format("H:i:s.v");

如果 microtime(true) 剛好返回一個小數點後全為零的浮點數,則嘗試 format() 將會返回一個致命錯誤。這是因為 DateTime::createFromFormat('U.u', $aFloatWithAllZeros) 會返回 false。

解決方法 (while 迴圈是用於測試解決方案是否有效)

$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
while (!is_bool($now)) {//用於測試解決方案}
$t = microtime(true);
$now = DateTime::createFromFormat('U.u', $t);
}
if (is_bool($now)) {//問題所在}
$now = DateTime::createFromFormat('U', $t);//解決方案}
}
$now = $now->format("H:i:s.v");
mariani dot v at sfeir dot com
11 個月前
當 microtime 返回非十進位浮點數時,避免錯誤最簡單的方法是使用 sprintf 將其結果轉換為浮點數。

$t = microtime(true);
$now = DateTime::createFromFormat('U.u', sprintf('%f', $t));
$now = $now->format("H:i:s.v");
To Top