22

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.

5
  • Couldn't you just pass 24*time.Hour to Truncate? Commented Jan 10, 2014 at 20:30
  • Yes, but only if you are using a timezone with no daylight savings time. Days are not always 24 hours. Commented Jan 10, 2014 at 20:48
  • days are almost never exactly 24 hours long Commented Jan 10, 2014 at 21:15
  • 1
    Are both times in the same timezone? If not, you need to be careful about what "on the same calendar day" means. Commented Jan 12, 2014 at 9:32
  • In this case they are the same timezone, but that is a good point. Commented Jan 13, 2014 at 19:38

4 Answers 4

38

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 } 
Sign up to request clarification or add additional context in comments.

3 Comments

I know this is a very old post, but would this not also compare the actual time, like hours and seconds instead of just they day, month and year?
it would not actually, check this out: pkg.go.dev/time#Time.Date, the Date() function will only return the year, month and day from the timestamp
Note: This does not account for times with different timezones. For example one time at 6pm ET will not equal a UTC timestamp for 7pm ET (which would be midnight UTC). You have to make sure you first convert both times to the same timezone first.
12
if a.Day() == b.Day() && a.Month() == b.Month() && a.Year() == b.Year() { // same date } 

Comments

3

You can truncate to days too, by using:

t.Truncate(time.Hour * 24) 

1 Comment

Apparently only works on UCT time, because it states in the Truncate() doc, that the calculation is performed "since the zero time", and in the Time type docs that "The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC." according to source
2

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) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.