Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count days between two dates in PHP?

Tags:

If I have a couple of strings $startDate and $endDate which are set to (for instance) "2011/07/01" and "2011/07/17" (meaning 1 July 2011 and 17 July 2011). How would I count the days from start date to end date? In the example given, it would be 17 days.

like image 399
cannyboy Avatar asked Sep 06 '10 19:09

cannyboy


People also ask

How can I calculate days between dates 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.

How can I compare two dates in PHP?

we can analyze the dates by simple comparison operator if the given dates are in a similar format. <? php $date1 = "2018-11-24"; $date2 = "2019-03-26"; if ($date1 > $date2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>

How do I calculate the number of weeks between two dates in PHP?

php function week_between_two_dates($date1, $date2) { $first = DateTime::createFromFormat('m/d/Y', $date1); $second = DateTime::createFromFormat('m/d/Y', $date2); if($date1 > $date2) return week_between_two_dates($date2, $date1); return floor($first->diff($second)->days/7); } $dt1 = '1/1/2014'; $dt2 = '12/31/2014'; ...

How can I find the difference between two days?

Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (1000*60*60*24) Print the final result using document.


2 Answers

Here is the raw way to do it

$startTimeStamp = strtotime("2011/07/01"); $endTimeStamp = strtotime("2011/07/17");  $timeDiff = abs($endTimeStamp - $startTimeStamp);  $numberDays = $timeDiff/86400;  // 86400 seconds in one day  // and you might want to convert to integer $numberDays = intval($numberDays); 
like image 150
axsuul Avatar answered Oct 07 '22 20:10

axsuul


Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11'); $datetime2 = new DateTime('2009-10-13'); $interval = $datetime1->diff($datetime2); 

Or:

$datetime1 = date_create('2009-10-11'); $datetime2 = date_create('2009-10-13'); $interval = date_diff($datetime1, $datetime2); 

You can then get the interval as a integer by calling $interval->days.

like image 27
wuputah Avatar answered Oct 07 '22 22:10

wuputah