Created
July 16, 2017 06:48
-
-
Save kasperhartwich/dbbf787c7a78428cbc5bf09fb4fae8f6 to your computer and use it in GitHub Desktop.
Fixes a bug with diffInMonths for DateTime/Carbon
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 | |
use Carbon\Carbon; | |
/** | |
* This fixes the bug in DateTime with diffInMonths! | |
* See this bugreport: https://github.com/briannesbitt/Carbon/issues/344 | |
*/ | |
class AppDate extends Carbon | |
{ | |
/** | |
* Get the difference in months | |
* | |
* @param \Carbon\Carbon|null $dt | |
* @param bool $abs Get the absolute of the difference | |
* | |
* @return int | |
*/ | |
public function diffInMonths(Carbon $dt = null, $abs = true) | |
{ | |
$dt = $dt ?: static::now($this->getTimezone()); | |
$months = 0; | |
if ($this->eq($dt)) { | |
return 0; | |
} else if ($this->lt($dt)) { | |
$diff_date = $this->copy(); | |
while ($diff_date->lt($dt)) { | |
$months++; | |
$diff_date->addMonth(); | |
} | |
return $months; | |
} else { | |
$dt = $dt->copy(); | |
while ($dt->lt($this)) { | |
$months++; | |
$dt->addMonth(); | |
} | |
return $months; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks a lot. As I've found a bug in php 5.6 with
data_diff
, I use nowCarbon
with your patch.