检查两个时间对象是否在Go中的同一日期上。

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

Check if two time objects are on the same Date in Go

问题

比较两个time.Time对象是否在同一天的最佳方法是什么?

我查看了使用t.Truncate()的方法,但它只能截断到小时。我知道可以使用t.GetDate(),这很直观,但仍然需要比我认为应该需要的更多代码行。

英文:

What is the best way to compare two time.Time objects to see if they are on the same calendar day?

I looked at using t.Truncate() but it can only truncate to hours. I know I can use t.GetDate() which is straightforward but still requires more lines of code than I think should be necessary.

答案1

得分: 32

将日期组件的时间解析为年、月和日,通过分别调用单独的方法三次,效率低下。应该使用一次方法调用来获取所有三个日期组件。根据我的基准测试,这样做几乎快了三倍。例如,

import "time"

func DateEqual(date1, date2 time.Time) bool {
    y1, m1, d1 := date1.Date()
    y2, m2, d2 := date2.Date()
    return y1 == y2 && m1 == m2 && d1 == d2
}
英文:

It's inefficient to parse the time for the date components three times by making separate method calls for the year, month, and day. Use a single method call for all three date components. From my benchmarks, it's nearly three times faster. For example,

import "time"

func DateEqual(date1, date2 time.Time) bool {
	y1, m1, d1 := date1.Date()
	y2, m2, d2 := date2.Date()
	return y1 == y2 && m1 == m2 && d1 == d2
}

答案2

得分: 10

如果 a.Day() == b.Day() && a.Month() == b.Month() && a.Year() == b.Year() {
// 相同的日期
}

英文:
if a.Day() == b.Day() && a.Month() == b.Month() && a.Year() == b.Year() {
    // same date
}

答案3

得分: 2

你也可以通过使用以下代码将时间截断为天:

t.Truncate(time.Hour * 24)
英文:

You can truncate to days too, by using:

t.Truncate(time.Hour * 24)

答案4

得分: 0

另一种方法是获取两个时间的日期的字符串表示,然后进行比较:

func sameDay(date, another time.Time) bool {
	return date.Format(time.DateOnly) == another.Format(time.DateOnly)
}
英文:

Another way around this is to get the string representation of dates from both times and compare them:

func sameDay(date, another time.Time) bool {
	return date.Format(time.DateOnly) == another.Format(time.DateOnly)
}

huangapple
  • 本文由 发表于 2014年1月11日 04:03:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/21053427.html
匿名

发表评论

匿名网友

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

确定