rtom
rtom

Reputation: 209

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

Upvotes: 0

Views: 123

Answers (2)

rescobar
rescobar

Reputation: 1305

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;

Upvotes: 1

Gagan Prajapati
Gagan Prajapati

Reputation: 140

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

Upvotes: 1

Related Questions