PHP DateTime object - time and time conflict

From a DateTime object, I'm interested in getting time in different time zones. As explained in a DateTime :: setTimezone doc, this works very well when a DateTime object is created from a string:

$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru')); echo $date->format('Ymd H:i:sP') . "\n"; $date->setTimezone(new DateTimeZone('Pacific/Chatham')); echo $date->format('Ymd H:i:sP') . "\n"; $date->setTimezone(new DateTimeZone('UTC')); echo $date->format('Ymd H:i:sP') . "\n"; echo $date->getTimestamp() . "\n"; 

The above examples 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 for the interesting part: if we pick up our timestamp and initiate our DateTime object with it in accordance with the instructions in the manual.

 $date2 = new DateTime('@946641600'); $date2->setTimezone(new DateTimeZone('Pacific/Nauru')); echo $date2->format('Ymd H:i:sP') . "\n"; $date2->setTimezone(new DateTimeZone('Pacific/Chatham')); echo $date2->format('Ymd H:i:sP') . "\n"; $date2->setTimezone(new DateTimeZone('UTC')); echo $date2->format('Ymd H:i:sP') . "\n"; echo $date2->getTimestamp() . "\n"; 

And here we get: // [edit] humm ... Sorry, this result 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 can no longer change the time zone!?!

Is it PHP or is it me? Version 5.3.15

+6
source share
2 answers

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

+2
source

Good, so I got angry myself. Of course, I'm the one who is wrong ...
To get it straight, I'll just pick up the bits that are relevant in the document here and.
The manual says:

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

So, you can use setTimezone to get the time in your time zone again (what can you expect if your system is configured this way!):

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

note that

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

misleading as you will be in UTC anyway! (and yes, this is very clearly indicated in the constructor's document. Therefore, be careful;)

Thanks @hakre Thanks everyone!

+5
source

Source: https://habr.com/ru/post/927943/


All Articles