strtotime / 86400 not returning even number of days
I am having a strange result with PHP Version 5.3.1, can anyone explain the below result?
$secondsDiff = strt开发者_如何学Cotime(date("2011-11-10")) - strtotime('2011-07-15');
return ($secondsDiff/86400);
it returns 117.958333333??
When I use dates closer together it generally works.
I had a look through the docs, but couldnt find any reference to this. Is this a known php bug that I just need to learn to live with or am I missing something very obvious?
This is probably due to a DST switch, which will increase or decrease the length of the period by an hour.
This could be fixed by rounding, or - more elegantly - by PHP 5.3's fancy new DateInterval class which can format periods as days and more.
Stolen from the manual:
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Don't convert seconds into days by dividing them by 86400. It will work most of the time, sure, but in some circumstances it will return an ugly number. That is what is happening here. The usual culprit is a switch into or out of daylight savings time.
The slow way to do it is to use a loop and calls to mktime()
; the modern way is to use the DateInterval
class.
The strtotime()
function uses the TZ environment variable. This means that when you convert that date, you end up with a timestamp that isn't exactly at midnight, unless you happen to have your timezone set up for GMT.
So, if you are in an area with daylight savings time, then a date in November will be an hour off than one in July. You can easily test this using the two dates you provided. On my server, one appears at 4:00AM, and the other at 5:00AM on their respective dates.
Another solution: Add UTC to the string as in
$datetime1 = new DateTime('2009-10-11 UTC');
$datetime2 = new DateTime('2009-10-13 UTC');
精彩评论