Finding days between 2 unix timestamps in php

dotty picture dotty · Nov 2, 2010 · Viewed 56.7k times · Source

Hay, i have a database holding events. There are 2 fields 'start' and 'end', these contain timestamps. When an admin enters these dates, they only have the ability to set the day,month,year. So we are only dealing with stamps containing days,months,years, not hours,minutes,seconds (hours,minutes and seconds are set to 0,0,0).

I have an event with the start time as 1262304000 and the end time as 1262908800. These convert to Jan 1 2010 and Jan 8 2010. How would i get all the days between these timestamps? I want to be able to return Jan 2 2010 (1262390400), Jan 3 2010 (1262476800) .. all the way to the end stamp. These events could cross over into different months, say May 28 to June 14.

Any ideas how to do this?

Answer

Vincent Savard picture Vincent Savard · Nov 2, 2010

You just have to calculate the number of seconds between the two dates, then divide to get days :

$numDays = abs($smallestTimestamp - $biggestTimestamp)/60/60/24;

Then, you can use a for loop to retrieve the dates :

$numDays = abs($smallestTimestamp - $biggestTimestamp)/60/60/24;

for ($i = 1; $i < $numDays; $i++) {
    echo date('Y m d', strtotime("+{$i} day", $smallestTimestamp)) . '<br />';
}

Again, if you don't know which timestamp is the smallest, you can use the min() function (second argument in strtotime).