我想將此日期時間字串轉換2022-09-30T21:39:25.220185674Z為,yyyy-mm-dd hh:mm:ss但它每次都回傳 1970-01-01 01:00:00 。
嘗試過:date('Y-m-d H:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));或date('Y-m-d\TH:i:s', strtotime('2022-09-30T21:39:25.220185674Z'));
你能幫忙找出這是哪種格式以及我如何正確地在 PHP 中格式化這樣的字串嗎?
經歷了這個問題,或者這個問題無濟于事。
uj5u.com熱心網友回復:
這是一個帶有微秒的 ISO 8601 日期時間字串,其中Z時區"Zulu"或UTC 0 hours.
ISO 8601 可以這樣決議DateTime():
$string = '2022-09-30T21:39:25.220185Z';
//create DateTime object
$date = date_create_from_format( "Y-m-d\TH:i:s.uP" , $string);
echo $date->format( 'Y-m-d H:i:s.u' );
但是,這不適用于您的字串,因為u格式"Y-m-d\TH:i:s.uP"中的引數表示微秒,在 PHP 中最多為6 digits,而您的則為9.
您可以通過使用正則運算式從字串的微秒部分中洗掉所有上述 6 位數字來解決此問題,例如
$string = '2022-09-30T21:39:25.220185674Z';
$new_string = preg_replace( '/^.*?\.\d{0,6}\K\d*/' , '' , $string );
$date = date_create_from_format( "Y-m-d\TH:i:s.uP" , $new_string );
echo $date->format('Y-m-d H:i:s.u');
輸出:2022-09-30 21:39:25.220180
正則運算式解釋:
1. ^.*?\.\d{0,6} // select from the begin everything including the dot
// and max 6 digits
2. \K // forget the previous match and start again from the
// point where 1. ended
3. \d* // select all digits left
4. replace the match with ""
uj5u.com熱心網友回復:
和 '?' 格式中,第 6 位之后的所有數字都可以被截去。
$string = '2022-09-30T21:39:25.220185123Z';
$date = date_create_from_format( "Y-m-d\TH:i:s.u???P" , $string);
var_dump($date);
https://3v4l.org/Upm6v
從 PHP 版本 8.0.10 開始,DateTime 可以毫無問題地識別像 '2022-09-30T21:39:25.220185674Z' 這樣的字串。
$str = '2022-09-30T21:39:25.220185674Z';
$d = new DateTime($str);
var_dump($d);
/*
object(DateTime)#1 (3) {
["date"]=>
string(26) "2022-09-30 21:39:25.220185"
["timezone_type"]=>
int(2)
["timezone"]=>
string(1) "Z"
}
*/
https://3v4l.org/pI4kO
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513115.html
