Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding days between 2 unix timestamps in php

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?

like image 381
dotty Avatar asked Nov 02 '10 16:11

dotty


People also ask

How to to calculate days between two timestamp in php?

The date_diff() function is an inbuilt function in PHP that is used to calculate the difference between two dates. This function returns a DateInterval object on the success and returns FALSE on failure.

What is Unix timestamp in PHP?

Simply put, the Unix timestamp is a way to track time as a running total of seconds. This count starts at the Unix Epoch on January 1st, 1970 at UTC. Therefore, the Unix timestamp is merely the number of seconds between a particular date and the Unix Epoch.

How can I timestamp in PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

How do you find the day of the week from the epoch time?

In summary: day of week = (floor(T / 86400) + 4) mod 7. (This assumes that you want the day of week in UTC. If you want to calculate it for another time zone, you need to perform some addition or subtraction of hours and minutes on T first.)


1 Answers

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).

like image 178
Vincent Savard Avatar answered Oct 05 '22 00:10

Vincent Savard