get number of days between two dates 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: 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 4: Number of week days between two dates in php
You are given two string (dd-mm-yyyy) representing two date,
you have to find number of all weekdays present in between given dates.
function number_of_days($days, $start, $end) {
$start = strtotime($start); $end = strtotime($end);
$w = array(date('w', $start), date('w', $end));
$x = floor(($end-$start)/604800);
$sum = 0;
for ($day = 0;$day < 7;++$day) {
if ($days & pow(2, $day)) {
$sum += $x + ($w[0] > $w[1]?$w[0] <= $day || $day <= $w[1] : $w[0] <= $day && $day <= $w[1]);
}
}
return $sum;
}
function getWeeklyDayNumbers($startDate, $endDate) {
$weekdays = array('monday' => 0, 'tuesday' => 0, 'wednesday' => 0, 'thursday' => 0, 'friday' => 0, 'saturday' => 0, 'sunday' => 0);
$weekdays['monday'] += number_of_days(0x02, $startDate, $endDate);
$weekdays['tuesday'] += number_of_days(0x04, $startDate, $endDate);
$weekdays['wednesday'] += number_of_days(0x08, $startDate, $endDate);
$weekdays['thursday'] += number_of_days(0x10, $startDate, $endDate);
$weekdays['friday'] += number_of_days(0x20, $startDate, $endDate);
$weekdays['saturday'] += number_of_days(0x40, $startDate, $endDate);
$weekdays['sunday'] += number_of_days(0x01, $startDate, $endDate);
return $weekdays;
}
$weekdays = getWeeklyDayNumbers('01-01-2021', '31-01-2021');
print_r($weekdays);exit;