[英]Convert date string to UTC time with PHP
我有以下日期字符串
$date="Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)"
我想将其转换为 UTC 时间
$timestamp_UNIX = strtotime($date);
echo date("Y-m-d\TH:i:s\Z",$timestamp_UNIX);
为什么我得到
2011-04-30T11:47:47Z
and not
2011-04-30T09:47:47Z
问题是您的代码不会自动回显UTC。 无论您的默认时区设置为什么,它都会回显时间戳。 这是在运行时通过date_default_timezone_set()
或通过date.timezone
中的配置设置 date.timezone php.ini
的。
现代方法是使用DateTime
和DateTimeZone
类。
$d = new DateTime('Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)');
print_r($d);
$d->setTimezone(new DateTimeZone('UTC'));
print_r($d);
印刷
DateTime Object
(
[date] => 2011-04-30 18:47:47
[timezone_type] => 1
[timezone] => +09:00
)
DateTime Object
(
[date] => 2011-04-30 09:47:47
[timezone_type] => 3
[timezone] => UTC
)
您应该使用gmdate()
而不是date()
(或者您可以检查 PHP 5.2 / 5.3 中的 DateTime 和 DateTimeZone 类)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.