note 118128 added to dateinterval.format

From: Date: Fri, 09 Oct 2015 10:33:21 +0000
Subject: note 118128 added to dateinterval.format
Groups: php.notes 
Request: Send a blank email to php-notes+get-203929@lists.php.net to get a copy of this message
If you want the difference between two timestamps in HOURS, do not forget to add the number of days: <?php // Bad example $lastEntryDate = new \DateTime('2015-05-23 00:10:20', new \DateTimeZone('UTC')); $dateDifference = $lastEntryDate->diff(new \DateTime('2015-05-25 02:35:45', new \DateTimeZone('UTC'))); var_dump((int)$dateDifference->format('%H')); // Returns 2 if ((int)$dateDifference->format('%H') > 24) { // Will never enter here, (int)$dateDifference->format('%H') will contain 0-23 ONLY } ?> Instead, sum the days: <?php // Bad example $lastEntryDate = new \DateTime('2015-05-23 00:10:20', new \DateTimeZone('UTC')); $dateDifference = $lastEntryDate->diff(new \DateTime('2015-05-25 02:35:45', new \DateTimeZone('UTC'))); var_dump(($dateDifference->days * 24 + (int)$dateDifference->format('%H'))); // Returns 50 if (($dateDifference->days * 24 + (int)$dateDifference->format('%H')) > 24) { // Will enter here now :) } ?> Hope this saves somebody some time and possible bugs :) ---- Server IP: 72.52.91.14 Probable Submitter: 88.159.158.133 ---- Manual Page -- http://php.net/manual/en/dateinterval.format.php Edit -- https://master.php.net/note/edit/118128 Del: integrated -- https://master.php.net/note/delete/118128/integrated Del: useless -- https://master.php.net/note/delete/118128/useless Del: bad code -- https://master.php.net/note/delete/118128/bad+code Del: spam -- https://master.php.net/note/delete/118128/spam Del: non-english -- https://master.php.net/note/delete/118128/non-english Del: in docs -- https://master.php.net/note/delete/118128/in+docs Del: other reasons-- https://master.php.net/note/delete/118128 Reject -- https://master.php.net/note/reject/118128 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203929) next »