convert timezone to another timezone

2019-02-25 04:17发布

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

However this will yield an output of "2012-11-07 15:05:26", which I'm pretty sure is wrong.

What could be I'm missing in here?

3条回答
Root(大扎)
2楼-- · 2019-02-25 05:10

Check this :

<?php

$time = "2012-11-07 15:05:26"; // fetch from database

$tz_object = new DateTimeZone('Europe/Berlin'); 
$datetime = new DateTime($time); 
$datetime->setTimezone($tz_object); 
echo $datetime->format('Y-m-d H:i:s');
//output 2012-11-07 10:35:26
?>
查看更多
姐就是有狂的资本
3楼-- · 2019-02-25 05:14

Maybe this could help. Just integrate it in your query to simplified your coding:

SELECT CONVERT_TZ('2012-11-07 15:05:26','+08:00','+01:00');

You can have more info here, regarding timezones you want to use. And here for more understanding

查看更多
神经病院院长
4楼-- · 2019-02-25 05:16

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().

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

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.

查看更多
登录 后发表回答