donglv6747
donglv6747
2016-01-27 16:16

仅将日期部分与时间进行比较.Golang中的时间

已采纳

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条回答

  • doujiaci7976 doujiaci7976 5年前

    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()
    
    点赞 评论 复制链接分享

相关推荐