Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DateTime object - Timestamp and Timezones conflict

From a DateTime object, I am interested in getting the time in different TimeZones. As explained in the DateTime::setTimezone doc, this works pretty well when the DateTime object is created from a string:

$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";

$date->setTimezone(new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:sP') . "\n";

echo $date->getTimestamp() . "\n";

The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
1999-12-31 12:00:00+00:00
946641600

Now is the interesting part: If we pick up our timestamp, and initiate our DateTime Object with it following the manual instructions.

$date2 = new DateTime('@946641600');

$date2->setTimezone(new DateTimeZone('Pacific/Nauru'));
echo $date2->format('Y-m-d H:i:sP') . "\n";

$date2->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date2->format('Y-m-d H:i:sP') . "\n";

$date2->setTimezone(new DateTimeZone('UTC'));
echo $date2->format('Y-m-d H:i:sP') . "\n";

echo $date2->getTimestamp() . "\n";

And here we get: // [edit] humm... Sorry, this output is wrong...
1999-12-31 12:00:00+00:00
1999-12-31 12:00:00+00:00
1999-12-31 12:00:00+00:00
946641600

UTC forever !!! We cannot change the timezone anymore !?!

Is it PHP or is it me ? Version 5.3.15

like image 845
mika Avatar asked Oct 17 '12 13:10

mika


2 Answers

Ok, so I was getting mad by myself. Of course, I am the one to be wrong...
To get it straight, I'll just pick up the bits that are relevants in the doc here and here.
Manual says:

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

So indeed, you can use setTimezone to get times again in your timezone (which could be expected if your system is set up that way !):

$timezone = new DateTimeZone('Europe/Madrid');
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));

Note that

$date =  new DateTime('@1306123200', new DateTimeZone('Europe/Madrid'));

is misleading, since you will be in UTC anyways ! (and yes, it is very clearly specified in the constructor's doc. So be careful ;)

Thanks @hakre Thanks all !

like image 160
mika Avatar answered Oct 31 '22 14:10

mika


It's just you. As far as PHP is concerned, it's all fine and dandy, PHP manual covers this nicely: http://www.php.net/manual/en/datetime.construct.php

like image 41
hakre Avatar answered Oct 31 '22 15:10

hakre