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.
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
}
if a.Day() == b.Day() && a.Month() == b.Month() && a.Year() == b.Year() {
// same date
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With