how to calculate days between two dates in php code example
Example 1: php calculate date difference
$d1 = new DateTime("2018-01-10 00:00:00");
$d2 = new DateTime("2019-05-18 01:23:45");
$interval = $d1->diff($d2);
$diffInSeconds = $interval->s;
$diffInMinutes = $interval->i;
$diffInHours = $interval->h;
$diffInDays = $interval->d;
$diffInMonths = $interval->m;
$diffInYears = $interval->y;
$d1 = strtotime("2018-01-10 00:00:00");
$d2 = strtotime("2019-05-18 01:23:45");
$totalSecondsDiff = abs($d1-$d2);
$totalMinutesDiff = $totalSecondsDiff/60;
$totalHoursDiff = $totalSecondsDiff/60/60;
$totalDaysDiff = $totalSecondsDiff/60/60/24;
$totalMonthsDiff = $totalSecondsDiff/60/60/24/30;
$totalYearsDiff = $totalSecondsDiff/60/60/24/365;
Example 2: Get the number of days between two dates in PHP
$startDate = new DateTime("2019-10-27");
$endDate = new DateTime("2020-04-11");
$difference = $endDate->diff($startDate);
echo $difference->format("%a");
Example 3: php difference between two dates
$date1 = "2007-03-24";
$date2 = "2009-06-26";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
Example 4: how to calculate days between two dates in php
<?php
function dateDifference($start_date, $end_date)
{
$diff = strtotime($start_date) - strtotime($end_date);
return ceil(abs($diff / 86400));
}
$start_date = "2016-01-02";
$end_date = "2016-01-21";
$dateDiff = dateDifference($start_date, $end_date);
echo "Difference between two dates: " . $dateDiff . " Days ";
?>
Example 5: find days with name between two dates in php
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$from_date = new DateTime($from_date);
$to_date = new DateTime($to_date);
for ($date = $from_date; $date <= $to_date; $date->modify('+1 day')) {
echo $date->format('l') . "\n";
}
Example 6: Calculate the Difference Between Two Dates Using PHP
phpCopy$firstDate = "2019-01-01";
$secondDate = "2020-03-04";
$dateDifference = abs(strtotime($secondDate) - strtotime($firstDate));
$years = floor($dateDifference / (365 * 60 * 60 * 24));
$months = floor(($dateDifference - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
$days = floor(($dateDifference - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 *24) / (60 * 60 * 24));
echo $years." year, ".$months." months and ".$days." days";