I'm trying to compare two times from different timezones, and see whether one is before the other. How would I do this in golang?
Note: Basically I would like sfTime.Before(nyTime) == true
, but my example below would have sfTime.Before(nyTime) == false
. Suggestions on how to make this happen would be great.
For example, in this code...
layout := "2006-01-02 15:04 MST"
sfTime, _ := time.Parse(layout, "2017-03-01 12:00 PDT")
nyTime, _ := time.Parse(layout, "2017-03-01 12:00 EDT")
fmt.Printf("Are these times equal? %v
", sfTime.Equal(nyTime))
This prints:
Are these times equal? true
Unintuitively, even if you set them to be the same timezone, this only changes the timezone, but not the HH:mm
value.
layout := "2006-01-02 15:04 MST"
sfTime, _ := time.Parse(layout, "2017-03-01 12:00 PDT")
nyTime, _ := time.Parse(layout, "2017-03-01 12:00 EDT")
// Set timezone to UTC
utcLocation, _ := time.LoadLocation("UTC")
sfTime = sfTime.In(utcLocation)
nyTime = nyTime.In(utcLocation)
// Timezones should not be equal, but they are
fmt.Printf("Are these times still equal? %v
", sfTime.Equal(nyTime))
fmt.Printf("The New York Time: %v
", nyTime)
Prints
Are these times still equal? true
The New York Time: 2017-03-01 12:00:00 +0000 UTC