Time, Times and Half a Time

A while back I came across the following in an email:

echo "Hours difference = ".floor(($d2-$d1)/3600) . "<br>";
echo "Minutes difference = ".floor(($d2-$d1)/60) . "<br>";
echo "Seconds difference = " .($d2-$d1). "<br>";
echo "Month difference = ".floor(($d2-$d1)/2628000) . "<br>";
echo "Days difference = ".floor(($d2-$d1)/86400) . "<br>";
echo "Year difference = ".floor(($d2-$d1)/31536000) . "<br>";

Can you spot the bug(s)?

Epoch time is seductive in its apparent simplicity, but can come back to bite you.  The gotcha above is the assumption made that a day consists of 86400 seconds.  In fact, twice a year, a day can have more or fewer seconds: when we switch to DST and when we switch back.

So what to do?  There are various alternatives depending on what you used the magic number 86400 (or its multiples) for.  If you’re trying to calculate a date ‘x’ days in the future, you can do something like this:

$Timestamp = strtotime("+90 day", $Timestamp);

If you have two dates already and want to know the number of days between them, you can convert the dates to times and then divide by 86400 and round the result.   You can read all about it here:


In the comments at the bottom of the date function documentation you can find other helpful variations on the above theme (beware, some require specific versions of PHP).

You may need to clarify what level of precision is required in your calculations.  Are you looking for how many days (24 hour periods) are spanned by two epoch times or how many calendar dates?  Is an approximation good enough?  Are you ok with the result being rounded up?

Moral of the story: Using magic numbers for the number of seconds in a day (or any greater unit of time) can come back to bite you.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>