-1

I'm expecting these two time.Time instances are the same. But, I'm not sure why I got the compare result is false.

package main

import (
    "fmt"
    "time"
)

func main() {
    t := int64(1497029400000)

    locYangon, _ := time.LoadLocation("Asia/Yangon")
    dt := fromEpoch(t).In(locYangon)

    locYangon2, _ := time.LoadLocation("Asia/Yangon")
    dt2 := fromEpoch(t).In(locYangon2)

    fmt.Println(dt2 == dt)
}

func fromEpoch(jsDate int64) time.Time {
    return time.Unix(0, jsDate*int64(time.Millisecond))
}

Playground

If I change "Asia/Yangon" to "UTC", they are the same.

package main

import (
    "fmt"
    "time"
)

func main() {
    t := int64(1497029400000)

    locYangon, _ := time.LoadLocation("UTC")
    dt := fromEpoch(t).In(locYangon)

    locYangon2, _ := time.LoadLocation("UTC")
    dt2 := fromEpoch(t).In(locYangon2)

    fmt.Println(dt2 == dt)

}

func fromEpoch(jsDate int64) time.Time {
    return time.Unix(0, jsDate*int64(time.Millisecond))
}

Playground

Note: I'm aware of Equal method (in fact, I fixed with Equal method.) But after more testing, I found some interesting case which is "UTC" location vs "Asia/Yangon" location. I'm expecting either both equal or both not equal.

Update: Add another code snippet with "UTC". Update2: Update title to be more precise (I hope it will help to avoid duplication)

Soe Moe
  • 3,428
  • 1
  • 23
  • 32
  • 2
    From the time documentation: `Do not use == with Time values`. You must use the Equal method – JimB May 30 '17 at 15:06
  • 1
    The Location is stored as a pointer in the time struct, so you are comparing 2 different pointer values to Location structs which is why they're different. UTC just happens to be the default which uses a nil pointer value, and therefor are equal. This is an implementation detail, there's no reason to ever use the == with time values, and the behavior may change again with go1.9 which uses monotonic time. – JimB May 30 '17 at 15:32
  • @JimB thank you. Can u pls put it as answer so that I can accept? – Soe Moe May 30 '17 at 16:09
  • 1
    Related / possible duplicate of [Why do 2 time structs with the same date and time return false when compared with ==?](https://stackoverflow.com/questions/36614921/why-do-2-time-structs-with-the-same-date-and-time-return-false-when-compared-wit/36615458#36615458) – icza May 30 '17 at 19:29

1 Answers1

0

LoadLocation seems to return a pointer to a new value every time.

Anyway, the good way to compare dates is Equal:

fmt.Println(dt2.Equal(dt))

Playground: https://play.golang.org/p/9GW-LSF0wg.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119