From 57f1331decac4b4685499540f51e1e573625241f Mon Sep 17 00:00:00 2001 From: Alexandre Santos Date: Wed, 20 Jun 2018 16:03:49 +0100 Subject: [PATCH] Fix diff in months and added tests (#42) --- carbon.go | 2 +- carbon_test.go | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/carbon.go b/carbon.go index 3f7bd2f..b2f5105 100644 --- a/carbon.go +++ b/carbon.go @@ -1209,7 +1209,7 @@ func (c *Carbon) DiffInMonths(carb *Carbon, abs bool) int64 { } diffYr := c.Year() - carb.Year() - if diffYr > 1 { + if math.Abs(float64(diffYr)) > 1 { diff := c.DiffInYears(carb, abs)*monthsPerYear + m return absValue(abs, diff) diff --git a/carbon_test.go b/carbon_test.go index 12dbdef..226fcd0 100644 --- a/carbon_test.go +++ b/carbon_test.go @@ -1958,6 +1958,13 @@ func TestDiffInMonthsMoreThanOneYear(t *testing.T) { assert.EqualValues(t, 13, t1.DiffInMonths(t2, true)) } +func TestDiffInMonthsMoreThanTwoYears(t *testing.T) { + t1, _ := Create(2018, time.August, 4, 1, 0, 0, 0, "UTC") + t2, _ := Create(2025, time.July, 3, 1, 0, 0, 0, "UTC") + + assert.EqualValues(t, 82, t1.DiffInMonths(t2, true)) +} + func TestDiffInMonthsOneDayDifference(t *testing.T) { t1, _ := Create(2016, time.September, 1, 10, 0, 0, 0, "UTC") t2, _ := Create(2016, time.August, 31, 10, 0, 0, 0, "UTC")