将时区转换到另一个时区 [英] convert timezone to another timezone
问题描述
我想转换从数据库中获取的日期,通过 CURRENT_TIMESTAMP
生成并存储在时间戳
列类型,从GMT + 8到GMT + 1。
I want to convert the date I fetched from the database, which is generated via CURRENT_TIMESTAMP
and stored in a timestamp
column type, from GMT+8 to GMT+1.
$time = "2012-11-07 15:05:26"; // fetch from database
$date = new DateTime($time, new DateTimeZone('Europe/Berlin'));
echo $date->format('Y-m-d H:i:s');
但是这会产生一个的输出2012-11-07 15:05:26 ,我确定是错误的。
However this will yield an output of "2012-11-07 15:05:26", which I'm pretty sure is wrong.
这里可能是什么?
推荐答案
首先,您需要使用原始时区实例化datetime对象。然后,在datetime对象被实例化之后,请使用 DateTime:调整时区: :setTimezone()
。
First, you need to instantiate the datetime object with the original timezone. Then, after the datetime object is instantiated, adjust the timezone with DateTime::setTimezone()
.
看到这段代码,我使用过 Asia / Hong_Kong
作为示例GMT + 8时区:
See this code, where I've used Asia/Hong_Kong
as an example GMT+8 timezone:
$time = "2012-11-07 15:05:26"; // fetch from database
$date = new DateTime($time,new DateTimeZone('Asia/Hong_Kong'));
$date->setTimezone(new DateTimeZone('Europe/Berlin'));
echo $date->format('Y-m-d H:i:s'); // yields 2012-11-07 08:05:26
如果所有原始日期始终一致意味着GMT + 8,您的PHP应用程序也设置为使用GMT + 8(设置为 date_default_timezone_set()
),没有必要通过初始的 DateTimeZone
对象,新创建的 DateTime
对象将自动使用该时区创建。
If all the original dates are always consistently meant as GMT+8, and your PHP application is set to use GMT+8 as well (set with date_default_timezone_set()
, for instance), there's no need to pass the initial DateTimeZone
object, as newly created DateTime
objects will automatically be created with that timezone.
这篇关于将时区转换到另一个时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!