Reputation: 679
I'm trying to use Carbon to return the difference in months, but I want it to be calendar months, not calculated months.
$diff = Carbon::parse('2019-06-30')->diffInMonths(Carbon::parse('2019-07-01'), false);
dd($diff); //returns 0
Does anybody know if there's a simple way to do this in Carbon?
The reason is to apply a discount to a base rate if a certain number of months has passed since the item went on sale, and calculate the discount based on how many calendar months have gone by.
Upvotes: 3
Views: 10778
Reputation: 11
the floorMonth() is completely wrong idea, just think if the date is 2022/09/14 04:01:00 and the next date is 2022/10/14 04/01:00, at this one, the difference is one month, but if we consider the 2022/09/14 04:02:00 and he next date to be 2022/10/14 04/01:00, then the difference of month is not one, it is zero, so the best solution to calculate is:
$this_month = Carbon::parse('2019-07-05');
$start_month = Carbon::parse('2019-06-30');
$diff = $start_month->diffInMonths($this_month);
Upvotes: 1
Reputation: 679
In case this helps anybody else, Carbon has rounding features (https://carbon.nesbot.com/docs/#api-modifiers), so you can round the month down using floorMonth();
$this_month = Carbon::parse('2019-07-05')->floorMonth(); // returns 2019-07-01
$start_month = Carbon::parse('2019-06-30')->floorMonth(); // returns 2019-06-01
$diff = $start_month->diffInMonths($this_month); // returns 1
Upvotes: 6