在Golang中,只比较time.Time的日期部分。

huangapple go评论77阅读模式
英文:

Compare only date part ot time.Time in Golang

问题

假设有以下两个日期。日期相同,但时间不同。

t1, _ := time.Parse("2006-01-02 15:04:05", "2016-01-01 12:12:12.0")
t2, _ := time.Parse("2006-01-02 15:04:05", "2016-01-01 18:19:20.0")

我想使用Format()进行比较,但不确定这是否是最好的方法,尤其是在涉及不同时区时。

if t1.Format("2006-01-02") == t2.Format("2006-01-02") {
    // 日期相等,不考虑时间。
}

这种方法可行吗?还是我漏掉了什么?

英文:

Assume the following two dates. The date is the same, however the time is different.

t1, _ := time.Parse("2006-01-02 15:04:05", "2016-01-01 12:12:12.0")
t2, _ := time.Parse("2006-01-02 15:04:05", "2016-01-01 18:19:20.0")

I would compare them using Format(), but am not sure if that's the best way, especially when different timezones are at play.

if t1.Format("2006-01-02") == t2.Format("2006-01-02") {
    // dates are equal, don't care about time.
}

Is this a good approach, or am I missing something?

答案1

得分: 57

你可以将时间截断到天:

t1.Truncate(24*time.Hour).Equal(t2.Truncate(24*time.Hour))

或者你可以分别比较年份和天数:

t1.Year() == t2.Year() && t1.YearDay() == t2.YearDay()
英文:

You can either truncate the time to the day:

t1.Truncate(24*time.Hour).Equal(t2.Truncate(24*time.Hour))

Or you can compare the year and day separately:

t1.Year() == t2.Year() && t1.YearDay() == t2.YearDay()

huangapple
  • 本文由 发表于 2016年1月28日 00:16:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/35042515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定