Skip to content

Commit

Permalink
Fix bug in DiffInMonths method output error
Browse files Browse the repository at this point in the history
  • Loading branch information
gouguoyin committed Aug 22, 2023
1 parent 86fe55c commit 6990f4a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
20 changes: 18 additions & 2 deletions difference.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,27 @@ func (c Carbon) DiffAbsInYears(carbon ...Carbon) int64 {
// DiffInMonths gets the difference in months.
// 相差多少月
func (c Carbon) DiffInMonths(carbon ...Carbon) int64 {
start, end := c, c.Now()
end := c.Now()
if len(carbon) > 0 {
end = carbon[len(carbon)-1]
}
return int64(math.Floor(float64((end.Timestamp() - start.Timestamp()) / (30 * 24 * 3600))))
startYear, startMonth, startDay := c.Date()
endYear, endMonth, endDay := end.Date()

diffYear, diffMonth, diffDay := endYear-startYear, endMonth-startMonth, endDay-startDay
if diffDay < 0 {
diffMonth = diffMonth - 1
}
if diffYear == 0 && diffMonth == 0 {
return int64(0)
}
if diffYear == 0 && diffMonth != 0 && diffDay != 0 {
if int(end.DiffAbsInHours(c)) < c.DaysInMonth()*HoursPerDay {
return int64(0)
}
return int64(diffMonth)
}
return int64(diffYear*MonthsPerYear + diffMonth)
}

// DiffAbsInMonths gets the difference in months with absolute value.
Expand Down
4 changes: 2 additions & 2 deletions difference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func TestCarbon_DiffInMonths(t *testing.T) {
{"2020-08-05 13:14:15", "2020-09-06 13:14:59", 1},
{"2020-12-31 13:14:15", "2021-01-31 13:14:15", 1},
{"2020-08-05 13:14:15", "2021-08-28 13:14:59", 12},
{"2020-08-05 13:14:15", "2018-08-28 13:14:59", -23},
{"2020-08-05 13:14:15", "2018-08-28 13:14:59", -24},
}

for index, test := range tests {
Expand All @@ -85,7 +85,7 @@ func TestCarbon_DiffAbsInMonths(t *testing.T) {
{"2020-08-05 13:14:15", "2020-07-28 13:14:00", 0},
{"2020-12-31 13:14:15", "2021-01-01 13:14:15", 0},
{"2020-08-05 13:14:15", "2021-08-28 13:14:59", 12},
{"2020-08-05 13:14:15", "2018-08-28 13:14:59", 23},
{"2020-08-05 13:14:15", "2018-08-28 13:14:59", 24},
}

for index, test := range tests {
Expand Down

0 comments on commit 6990f4a

Please sign in to comment.