Christian Giacomi

An attempt at a small developer blog

Check if two Time objects are the same point in time in Go

Posted at — Oct 14, 2019   Category — software 

How do you check if two Time objects in Go refer to the same point in time?

Well in Go unlike Javascript it is extremely simple. The Go standard library has this functionality built in, as long as you are comparing both date and time.

In the Time Package, there is a Function for the Time struct that can do the job for us. As an extra bonus, this function will also take into account timezones. This will allow us to check for equality across timezones.

The function is defined like this

func (t Time) Equal(u Time) bool

And this is how you can use it, if you want to check that two timestamps are in effect the same point in time in two different timezones, or in the same timezone.

package main

import (
	"fmt"
	"time"
)

func main() {
	rome, _ := time.LoadLocation("Europe/Rome")	
	london, _ := time.LoadLocation("Europe/London")
	
	dateR := time.Date(2019, 12, 25, 3, 30, 0, 0, rome)
	dateL := time.Date(2019, 12, 25, 2, 30, 0, 0, london)

	fmt.Printf("equal: %v\n", dateR == dateL)
	fmt.Printf("equal: %v\n", dateR.Equal(dateL))
}

Should you instead just want compare dates and are not interested in the time part of the object, then you will need to write your own function to do the comparison.

There are several ways you can do this, but this is the simplest way I have found.

import "time"

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

As you can see it’s extremely simple to compare Time objects in Go, even if you have to roll your own implementation to compare Dates.

If this post was helpful tweet it or share it.