Skip to content

Commit

Permalink
Fix 'DiffInYears' method
Browse files Browse the repository at this point in the history
  • Loading branch information
gouguoyin committed Sep 6, 2023
1 parent 42c4705 commit baae976
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
13 changes: 12 additions & 1 deletion difference.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package carbon

import (
"fmt"
"math"
"strings"
)
Expand All @@ -12,7 +13,15 @@ func (c Carbon) DiffInYears(carbon ...Carbon) int64 {
if len(carbon) > 0 {
end = carbon[len(carbon)-1]
}
return int64(math.Floor(float64((end.Timestamp() - start.Timestamp()) / (365 * 24 * 3600))))

dy, dm, dd := end.Year()-start.Year(), end.Month()-start.Month(), end.Day()-start.Day()
if dd < 0 || dm < 0 {
dy--
}
if dy < 0 && (dd != 0 || dm != 0) {
dy++
}
return int64(dy)
}

// DiffAbsInYears gets the difference in years with absolute value.
Expand Down Expand Up @@ -211,6 +220,8 @@ func (c Carbon) DiffForHumans(carbon ...Carbon) string {
// gets the difference for unit and value.
// 获取相差单位和差值
func (c Carbon) diff(end Carbon) (unit string, value int64) {
fmt.Println("ss:", c.DiffAbsInYears(end))

switch true {
case c.DiffAbsInYears(end) > 0:
unit = "year"
Expand Down
1 change: 1 addition & 0 deletions difference_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ func TestCarbon_DiffInYears(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", 1},
{"2018-08-28 13:14:59", "2020-08-05 13:14:15", 1},
{"2020-08-05 13:14:15", "2018-08-28 13:14:59", -1},
}

Expand Down

0 comments on commit baae976

Please sign in to comment.