fishcracker
fishcracker

Reputation: 2509

convert timezone to another timezone

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?

Upvotes: 3

Views: 565

Answers (3)

Decent Dabbler
Decent Dabbler

Reputation: 22773

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.

Upvotes: 3

sephoy08
sephoy08

Reputation: 1114

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

Upvotes: 1

metalfight - user868766
metalfight - user868766

Reputation: 2750

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
?>

Upvotes: 0

Related Questions