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.
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.
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"; ?>
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'; ...
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.
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With