note 117238 added to datetime.settimestamp

From: Date: Thu, 07 May 2015 21:32:55 +0000
Subject: note 117238 added to datetime.settimestamp
Groups: php.notes 
Request: Send a blank email to php-notes+get-202469@lists.php.net to get a copy of this message
It should be noted above, be careful when manipulating the DateTime object with unix timestamps. In the above examples you will get varying results dependent on your current timezone, method used, and version of PHP. One would expect all of the examples above to perform the same as setTimestamp() or date('H:i', $timestamp); would. <?php date_default_timezone_set('America/New_York'); $ts = 1171502725; ?> Set timestamp from UTC timezone use UTC timezone <?php $date = new DateTime("@$ts"); var_dump($date->format('Y-m-d H:i:s e')); /* string(26) "2007-02-15 01:25:25 +00:00" //PHP 5.3.0 - 5.6.8 */ ?> To convert the above to use the current timezone simply use <?php $date->setTimezone(date_default_timezone_get()); //string(36) "2007-02-14 20:25:25 America/New_York" ?> Set the timestamp from UTC timezone use current timezone <?php $date = new DateTime; $date->modify('@' . $ts); var_dump($date->format('Y-m-d H:i:s e')); /* string(36) "2007-02-15 01:25:25 America/New_York" //PHP 5.3.6 - 5.6.8 string(36) "2052-06-20 18:53:24 America/New_York" //PHP 5.3.0 - 5.3.5 */ ?> Set the timestamp from current timezone use current timezone <?php $date = new DateTime; $date->setTimestamp($ts); var_dump($date->format('Y-m-d H:i:s e')); /* string(36) "2007-02-14 20:25:25 America/New_York" //PHP 5.3.0 - 5.6.8 */ ?> ---- Server IP: 72.52.91.14 Probable Submitter: 50.79.80.225 ---- Manual Page -- http://php.net/manual/en/datetime.settimestamp.php Edit -- https://master.php.net/note/edit/117238 Del: integrated -- https://master.php.net/note/delete/117238/integrated Del: useless -- https://master.php.net/note/delete/117238/useless Del: bad code -- https://master.php.net/note/delete/117238/bad+code Del: spam -- https://master.php.net/note/delete/117238/spam Del: non-english -- https://master.php.net/note/delete/117238/non-english Del: in docs -- https://master.php.net/note/delete/117238/in+docs Del: other reasons-- https://master.php.net/note/delete/117238 Reject -- https://master.php.net/note/reject/117238 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#202469) next »