diff --git a/carbon.go b/carbon.go index b2f5105..6655661 100644 --- a/carbon.go +++ b/carbon.go @@ -1187,7 +1187,7 @@ func (c *Carbon) DiffInMonths(carb *Carbon, abs bool) int64 { if (diffHr - hrLastMonth) >= 0 { var m int64 if c.Year() < carb.Year() { - m = (int64(monthsPerYear) - int64(c.In(time.UTC).Month())) + (int64(carb.In(time.UTC).Month()) - 1) + m = int64(monthsPerYear) - int64(c.In(time.UTC).Month()) + int64(carb.In(time.UTC).Month()) - 1 totalHr := int64(c.DaysInMonth() * hoursPerDay) cHr := c.StartOfMonth().DiffInHours(c, abs) remainHr := totalHr - cHr @@ -1210,7 +1210,8 @@ func (c *Carbon) DiffInMonths(carb *Carbon, abs bool) int64 { diffYr := c.Year() - carb.Year() if math.Abs(float64(diffYr)) > 1 { - diff := c.DiffInYears(carb, abs)*monthsPerYear + m + dateWithoutMonths := c.AddMonths(int(m)) + diff := dateWithoutMonths.DiffInYears(carb, abs)*monthsPerYear + m return absValue(abs, diff) } diff --git a/carbon_test.go b/carbon_test.go index 226fcd0..1a5ab2f 100644 --- a/carbon_test.go +++ b/carbon_test.go @@ -1993,6 +1993,13 @@ func TestDiffInMonthsSameMonth(t *testing.T) { assert.EqualValues(t, 0, t1.DiffInMonths(t2, true)) } +func TestDiffInMonthsDifferentYears(t *testing.T) { + t1, _ := Create(2018, time.May, 1, 0, 0, 0, 0, "UTC") + t2, _ := Create(2020, time.June, 1, 0, 0, 0, 0, "UTC") + + assert.EqualValues(t, 25, t1.DiffInMonths(t2, true)) +} + func TestDiffInString(t *testing.T) { t1, _ := Create(2016, time.August, 10, 10, 0, 0, 0, "UTC") t2, _ := Create(2016, time.August, 1, 23, 0, 0, 0, "UTC")