使用PHP将日期字符串转换为UTC时间 [英] Convert date string to UTC time with PHP

查看:131
本文介绍了使用PHP将日期字符串转换为UTC时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日期字符串

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

我想将其转换为UTC时间

I want to convert it to UTC time

$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 在您的 php.ini

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.

现代方式是使用 DateTime DateTimeZone 课程。

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);

打印

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
)

这篇关于使用PHP将日期字符串转换为UTC时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆