Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

time

go

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.

like image 895
Colin Gislason Avatar asked Jan 10 '14 20:01

Colin Gislason


2 Answers

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
}
like image 193
peterSO Avatar answered Oct 02 '22 08:10

peterSO


if a.Day() == b.Day() && a.Month() == b.Month() && a.Year() == b.Year() {
    // same date
}
like image 35
thwd Avatar answered Oct 02 '22 08:10

thwd