Skip to content

Instantly share code, notes, and snippets.

@heiglandreas
Last active September 2, 2021 06:17
Show Gist options
  • Save heiglandreas/531ef2c05f5584fa88d963586bd333e6 to your computer and use it in GitHub Desktop.
Save heiglandreas/531ef2c05f5584fa88d963586bd333e6 to your computer and use it in GitHub Desktop.
Get difference between two dates including a one-month difference when both dates are on the last day of a month regardles the actual date
<?php
namespace Org_Heigl\Date;
class DateInterval extends \DateInterval
{
public static function fromDates(DateTimeInterface $a, DateTimeInterface $b) : \DateInterval
{
$first = $a;
$second = $b;
if ($a > $b) {
$first = $b;
$second = $a;
}
$diff = $first->diff($second);
if (
$first->format('t') === $first->format('d') &&
$second->format('t') === $second->format('d')
) {
$numberOfMonths = $second->format('m') - $first->format('m');
$numberOfYears = $second->format('Y') - $first->format('Y');
$numberOfMonths += $numberOfYears * 12;
$diff->d = 0;
$diff->y = floor($numberOfMonths/12);
$diff->m = $numberOfMonths % 12;
}
return $diff;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment