独立实现 Duration.Abs 方法

This commit is contained in:
Peleus 2024-03-08 15:10:56 +08:00
parent a08087e583
commit 738e0aceaa

View File

@ -6,6 +6,11 @@ import (
"time" "time"
) )
const (
minDuration time.Duration = -1 << 63
maxDuration time.Duration = 1<<63 - 1
)
// DiffInYears gets the difference in years. // DiffInYears gets the difference in years.
// 相差多少年 // 相差多少年
func (c Carbon) DiffInYears(carbon ...Carbon) int64 { func (c Carbon) DiffInYears(carbon ...Carbon) int64 {
@ -202,14 +207,11 @@ func (c Carbon) DiffInDuration(carbon ...Carbon) time.Duration {
// DiffAbsInDuration gets the difference in duration with absolute value. // DiffAbsInDuration gets the difference in duration with absolute value.
// 相差时长(绝对值) // 相差时长(绝对值)
func (c Carbon) DiffAbsInDuration(carbon ...Carbon) time.Duration { func (c Carbon) DiffAbsInDuration(carbon ...Carbon) time.Duration {
end := c.Now() d := c.DiffInDuration(carbon...)
if c.IsSetTestNow() { if d >= 0 {
end = CreateFromTimestampNano(c.testNow, c.Location()) return d
} }
if len(carbon) > 0 { return -d
end = carbon[0]
}
return end.StdTime().Sub(c.StdTime()).Abs()
} }
// DiffForHumans gets the difference in a human-readable format, i18n is supported. // DiffForHumans gets the difference in a human-readable format, i18n is supported.