英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论