Last active
September 2, 2021 06:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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