I have to calculate duration between two dates and result it to years, months and date format, but its returning extra one or two days in a month, I couldn't able find where the issue is
Start date - 01-03-2024
End date - 31-03-2024
Duration - 1 month, 2 days (extra two days is wrong)
The function used for computation
function getDuration($startDate, $endDate)
{
if (empty($startDate) || empty($endDate)) {
return '';
}
$startDateTime = new DateTime($startDate);
$endDateTime = new DateTime($endDate);
$endDateTime->modify('+1 day');
$interval = $startDateTime->diff($endDateTime);
$duration = '';
if ($years = $interval->y) {
$duration .= "$years year" . ($years > 1 ? 's' : '') . ', ';
}
if ($months = $interval->m) {
$duration .= "$months month" . ($months > 1 ? 's' : '') . ', ';
}
if ($days = $interval->d) {
$duration .= "$days day" . ($days > 1 ? 's' : '');
}
return rtrim($duration, ', ');
}
The problem here is the start date and end date we pass shouldn't be a string value, We have to convert it to date format if it is in string format
and it Works !!!