简体   繁体   中英

Change timezone using DateTime doesn't change it

I am trying to change time according to timezone. I am getting time and timezone from DB, time looks like this 2017-02-23 12:37:19 and timezone is according to this manual page . I don't think the datetime has wrong format. But problem is that it doesn't convert the time from DB timezone, to timezone that I want to convert It.

$time = new DateTime($user['date'], new DateTimeZone($user['timezone']));
$user['date'] = $time->format('Y-m-d H:i:s');

Here is a way to do so.

$time = new DateTime($user['date'], new DateTimeZone($dbTimeZone));
//use $dbTimeZone as the timezone from which you want to convert to your user timezone

$time->setTimezone(new DateTimeZone($user['timezone']));

$user['date'] = $time->format('Y-m-d H:i:s');

You could sets the time zone, try this:

$user['timezone'] = 'Europe/Berlin';
$user['date'] = '2017-02-24 10:24:08';
$dbTimeZone = 'America/Vancouver';
$date = new \DateTime($user['date'], new \DateTimeZone($user['timezone']));
$date->setTimezone(new \DateTimeZone($dbTimeZone));
$sConvertedDate = $date->format('Y-m-d H:i:s');
echo $sConvertedDate;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM