Skip to content

Instantly share code, notes, and snippets.

@kasperhartwich
Created July 16, 2017 06:48
Show Gist options
  • Save kasperhartwich/dbbf787c7a78428cbc5bf09fb4fae8f6 to your computer and use it in GitHub Desktop.
Save kasperhartwich/dbbf787c7a78428cbc5bf09fb4fae8f6 to your computer and use it in GitHub Desktop.
Fixes a bug with diffInMonths for DateTime/Carbon
<?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;
}
}
}
@giak
Copy link

giak commented Mar 8, 2019

thanks a lot. As I've found a bug in php 5.6 with data_diff, I use now Carbon with your patch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment