PHP DateTime 与 TimeZone 到 MongoDB\BSON\UTCDateTime
问题:PHP DateTime 与 TimeZone 到 MongoDB\BSON\UTCDateTime
我需要 PHP DateTime 的帮助,将 TimeZone 转换为 MongoDB\BSON\UTCDateTime。如果我有字符串 "2015-10-20T04:02:00.608000+01:00" 它会给我一个 DateTime
$date = DateTime::createFromFormat( 'Y-m-d\TH:i:s.uT', $string );
DateTime
date => "2015-10-20 04:02:00.608000"
timezone_type => 1
timezone => "+01:00"
如果我将其转换为 MongoDB\BSON\UTCDateTime 并转换回 PHP DateTime
$mDate = new \MongoDB\BSON\UTCDateTime( $date->format('U') * 1000 );
$mDate->toDateTime()->setTimeZone(new DateTimeZone('Europe/Bratislava'))
我会得到正确的结果05:02
DateTime
date => "2015-10-20 05:02:00.000000"
timezone_type => 3
timezone => "Europe/Bratislava"
但是如果输入字符串有 +02:00 TimeZone "2015-10-20T04:02:00.608000+02:00" 并使用相同的方法,结果是
DateTime
date => "2015-10-20 04:02:00.000000"
timezone_type => 3
timezone => "Europe/Bratislava"
如果我期望 06:02,为什么第二个结果是 04:02?
解答
反应是正确的。当您在时间戳上添加+时区时,您实际上是从 UTC 向东移动。您不是 adding 到 UTC 时间,您实际上是从 UTC 时间中_减去_。这意味着2015-10-20T04:02:00.608000+01:00是世界标准时间凌晨 3 点。2015-10-20T04:02:00.608000+02:00是世界标准时间凌晨 2 点。如果您的时区偏移量不断提高,您可以更轻松地看到这一点
$date = DateTime::createFromFormat( 'Y-m-d\TH:i:s.uT', "2015-10-20T04:02:00.608000+01:00");
$mDate = new \MongoDB\BSON\UTCDateTime( $date->format('U') * 1000 );
var_dump($date, $mDate->toDateTime());
object(DateTime)#1 (3) {
["date"]=>
string(26) "2015-10-20 04:02:00.608000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+01:00"
}
object(DateTime)#3 (3) {
["date"]=>
string(26) "2015-10-20 03:02:00.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+00:00"
}
$date = DateTime::createFromFormat( 'Y-m-d\TH:i:s.uT', "2015-10-20T04:02:00.608000+02:00");
$mDate = new \MongoDB\BSON\UTCDateTime( $date->format('U') * 1000 );
var_dump($date, $mDate->toDateTime());
object(DateTime)#1 (3) {
["date"]=>
string(26) "2015-10-20 04:02:00.608000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+02:00"
}
object(DateTime)#3 (3) {
["date"]=>
string(26) "2015-10-20 02:02:00.000000"
["timezone_type"]=>
int(1)
["timezone"]=>
string(6) "+00:00"
}
MongoDB 存储 UTC 时间戳。当您添加Europe/Bratislava时区时,您是在说“这个 UTC 时间戳在布拉迪斯拉发的时间是什么时候”。对于 10 月(夏令时),相差 1 小时。
在旁注中。尝试 never 混合+XXXX和 Unicode/Olson 时区 (Europe/Bratislava)。由于夏令时,您最终会遇到一些非常奇怪的错误。如果您需要记录用户的本地时间以在某个时候显示回来,请使用可选的第三个参数创建您的DateTime对象,例如:
$customerTz = 'Europe/Bratislava';
$date = DateTime::createFromFormat( 'Y-m-d\TH:i:s.u', $dateString, $customerTz);
还要检查你是否真的需要创建一个DateTime,或者只是一个带有时间戳的新UTCDateTime并处理显示逻辑中的 tz。
更多推荐
所有评论(0)