phpstrtotime

How to calculate the interval between 2 unix timestamps in php WITHOUT dividing by 86400 (60*60*24)


I have 2 unix timestamps, I'm in AsiaPacific/Auckland timezone (GMT+12, DaylightSavings = GMT+13)

I want to calculate the number of days interval between 2 timestamps, where one is inside daylight savings time and one is not.

My example dates are:

7 Feb 2009 (1233925200) to 21 September 2010 (1284985360) (not including 21st) see here it says 591 days: http://www.timeanddate.com/date/durationresult.html?d1=7&m1=2&y1=2009&d2=21&m2=9&y2=2010

Let's calculate, here are my timestamps (both are based on Auckland 00:00 time)

1284985360-1233925200 = 51060160
51060160 / 86400 = 590.974

So yea I need 591. I don't want to use the "round up" solution

Is there any reliable method like strtotime, but for calculating date intervals, preferably that don't need php 5.3+ minimum

EDIT: need to clarify, I'm using STRTOTIME to get these timestamps, I thought that was UTC

EDIT2: I believe I have found the issue. While my end date was 21 September, I was actually using time() to get my end date, and time() was returning the wrong timestamp, perhaps it doesn't account for the GMT+12, regardless I switched time() to strtotime(date('d M Y')) and it returned the correct timestamp! eureka 591 days


Solution

  • Calculate the number of full days for both timestamps before calculating the difference:

    floor(1284985360 / 86400) - floor(1233925200 / 86400)
    

    The your result is always an integer.

    And since you’re using strtotime to get these timestamps, specify the time 00:00:00+0000 to always get a multiple of 86400:

    strtotime($str.' 00:00:00+0000')