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
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 !
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With