Go time comparison

后端 未结 2 1775
生来不讨喜
生来不讨喜 2021-01-20 17:26

I\'m trying to create simple function just to change time zone of a time to another (Lets assume UTC to +0700 WIB). Here is the source code. I have 2 functions, first

2条回答
  •  情话喂你
    2021-01-20 17:40

    There is an .Equal() method to compare dates :

    if !res.Equal(expect) {
       ...
    

    Quoting the doc :

    Note that the Go == operator compares not just the time instant but also the Location and the monotonic clock reading. Therefore, Time values should not be used as map or database keys without first guaranteeing that the identical Location has been set for all values, which can be achieved through use of the UTC or Local method, and that the monotonic clock reading has been stripped by setting t = t.Round(0). In general, prefer t.Equal(u) to t == u, since t.Equal uses the most accurate comparison available and correctly handles the case when only one of its arguments has a monotonic clock reading.

    If you look at the code for the time.Time(*) struct, you can see that this struct has three private fields :

    type Time struct {
        ...
        wall uint64
        ext  int64
    
        ...
        loc *Location
    }
    

    and the comments about those fields clearly indicate that, depending on how the Time struct was built, two Time describing the same point in time may have different values for these fields.

    Running res == expect compares the values of these inner fields,
    running res.Equal(expect) tries to do the thing you expect.


    (*) time/time.go source code on master branch as of oct 27th, 2020

提交回复
热议问题