Skip to content

Commit

Permalink
Fix diff in months counting months twice
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexandre Santos committed Jun 20, 2018
1 parent ed4169d commit dc615c0
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
5 changes: 3 additions & 2 deletions carbon.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
Expand Down
7 changes: 7 additions & 0 deletions carbon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down

0 comments on commit dc615c0

Please sign in to comment.