Convert date string to UTC time with PHP

匿名 (未验证) 提交于 2019-12-03 02:36:02

问题:

I have the following date string

$date="Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)"

I want to convert it to UTC time

$timestamp_UNIX = strtotime($date); echo date("Y-m-d\TH:i:s\Z",$timestamp_UNIX);

Why do I got

2011-04-30T11:47:47Z and not 2011-04-30T09:47:47Z

回答1:

The problem is that you code does not automatically echo UTC. It echos the timestamp in whatever your default timezone is set to. This is done via date_default_timezone_set() at runtime or via the configuration setting date.timezone in your php.ini.

The modern way would be to use the DateTime and the DateTimeZone classes.

$d = new DateTime('Sat Apr 30 2011 18:47:47 GMT+0900 (Tokyo)'); print_r($d); $d->setTimezone(new DateTimeZone('UTC')); print_r($d);

prints

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 )


回答2:

You should use gmdate() instead of date() (or you could check the DateTime and DateTimeZone classes in PHP 5.2 / 5.3)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!