Skip to content

Commit

Permalink
[RFC] Fix incorrect diff in months (#74)
Browse files Browse the repository at this point in the history
* Fix incorrect diff in months

* Improve naming of test
  • Loading branch information
rntdrts authored Apr 16, 2022
1 parent 33bdc51 commit a000e35
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
12 changes: 10 additions & 2 deletions carbon.go
Original file line number Diff line number Diff line change
Expand Up @@ -1202,9 +1202,9 @@ func calculateDiffInMonths(c, carb *Carbon, abs bool) int64 {

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

if remainingTime < c.DaysInMonth()*hoursPerDay {
if remainingTime < totalHours {
return 0
}

Expand Down Expand Up @@ -1838,6 +1838,14 @@ func (c *Carbon) SetLocale(l string) error {
return nil
}

func calculateDiffInTimeAndHours(c, carb *Carbon) (int, int) {
if carb.Timestamp() < c.Timestamp() {
return int(c.DiffInHours(carb, true)), carb.DaysInMonth() * hoursPerDay
}

return int(carb.DiffInHours(c, true)), c.DaysInMonth() * hoursPerDay
}

/* TODO
// String Formatting
Expand Down
11 changes: 11 additions & 0 deletions carbon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2071,6 +2071,17 @@ func TestDiffInMonthsEnsureIsTruncated(t *testing.T) {
assert.EqualValues(t, 1, t1.DiffInMonths(t2, true))
}

func TestDiffInMonthsFor30DaysMonths(t *testing.T) {
d1, _ := Create(2020, time.November, 1, 0, 0, 0, 0, time.UTC.String())
d2, _ := Create(2020, time.December, 1, 0, 0, 0, 0, time.UTC.String())

months := d1.DiffInMonths(d2, true)
assert.EqualValues(t, 1, months)

monthsReverse := d2.DiffInMonths(d1, true)
assert.EqualValues(t, 1, monthsReverse)
}

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 a000e35

Please sign in to comment.