Skip to content

Commit

Permalink
[RFC] Add diffInMonths fix for NonUTC zones (#49)
Browse files Browse the repository at this point in the history
* Add diffInMonths fix for NonUTC zones

* Add test to reproduce issue (#46)

* Copy the instance

* Remove duplicated test
  • Loading branch information
Hugo Correia authored Dec 4, 2018
1 parent 26df394 commit 5c2074d
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
17 changes: 14 additions & 3 deletions carbon.go
Original file line number Diff line number Diff line change
Expand Up @@ -1187,12 +1187,23 @@ func (c *Carbon) DiffInMonths(carb *Carbon, abs bool) int64 {
carb = nowIn(c.Location())
}

cAux := c.Copy()
carbAux := carb.Copy()
if cAux.Location() != carbAux.Location() {
cAux = NewCarbon(cAux.In(time.UTC))
carbAux = NewCarbon(carbAux.In(time.UTC))
}

return calculateDiffInMonths(cAux, carbAux, abs)
}

func calculateDiffInMonths(c, carb *Carbon, abs bool) int64 {
if c.Month() == carb.Month() && c.Year() == carb.Year() {
return 0
}

if c.Month() != carb.Month() && c.Year() == carb.Year() {
diffInMonths := int64(carb.In(time.UTC).Month() - c.In(time.UTC).Month())
diffInMonths := int64(carb.Month() - c.Month())
remainingTime := int(carb.DiffInHours(c, true))

if remainingTime < c.DaysInMonth()*hoursPerDay {
Expand All @@ -1202,13 +1213,13 @@ func (c *Carbon) DiffInMonths(carb *Carbon, abs bool) int64 {
return absValue(abs, diffInMonths)
}

m := monthsPerYear - c.In(time.UTC).Month() + carb.In(time.UTC).Month() - 1
m := monthsPerYear - c.Month() + carb.Month() - 1
if c.Year() < carb.Year() && c.hasRemainingHours(carb) {
m = m + 1
}

if c.Year() > carb.Year() {
m = monthsPerYear - carb.In(time.UTC).Month() + c.In(time.UTC).Month() - 1
m = monthsPerYear - carb.Month() + c.Month() - 1

if carb.hasRemainingHours(c) {
m = m + 1
Expand Down
7 changes: 7 additions & 0 deletions carbon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2056,6 +2056,13 @@ func TestDiffInMonthsNegativeNoSign(t *testing.T) {
assert.EqualValues(t, 11, t1.DiffInMonths(t2, true))
}

func TestDiffInMonthsOverYearNonUTC(t *testing.T) {
t1, _ := Create(2018, time.December, 2, 0, 0, 0, 0, "EET")
t2, _ := Create(2019, time.February, 1, 0, 0, 0, 0, "EET")

assert.EqualValues(t, 1, t1.DiffInMonths(t2, true))
}

func TestDiffInMonthsEnsureIsTruncated(t *testing.T) {
t1, _ := Create(2018, time.January, 1, 0, 0, 0, 0, "UTC")
t2, _ := Create(2018, time.February, 17, 0, 0, 0, 0, "UTC")
Expand Down

0 comments on commit 5c2074d

Please sign in to comment.