How to use DateTime and DateInterval In PHP
In this approach, we are using the DateTime class in PHP to handle date calculations. By iterating through each day between the start and end dates and checking if it falls on a weekday (Monday to Friday), we count the number of business days. The DateInterval class helps increment the date by one day in each iteration, ensuring accurate business day calculations.
Example: The below example uses DateTime and DateInterval to calculate business days in PHP.
<?php
function getBusinessDays1($startDate, $endDate) {
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$businessDays = 0;
while ($start <= $end) {
$dayOfWeek = $start->format('N');
if ($dayOfWeek < 6) {
$businessDays++;
}
$start->add(new DateInterval('P1D'));
}
return $businessDays;
}
$startDate = '2024-05-01';
$endDate = '2024-05-10';
echo "Business days: "
. getBusinessDays1($startDate, $endDate);
?>
Output
Business days: 8
How to Calculate Business Days in PHP?
We have given two dates, our task is to write a PHP program to get total business days, i.e. weekdays between the two dates.
Below are the approaches to calculate business days in PHP:
Table of Content
- Using DateTime and DateInterval
- Using strtotime and date functions