Go time comparison

后端 未结 2 1777
生来不讨喜
生来不讨喜 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:55

    Dates in golang must be compared with Equal method. Method Date returns Time type.

    func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
    

    and Time type have Equal method.

    func (t Time) Equal(u Time) bool
    

    Equal reports whether t and u represent the same time instant. Two times can be equal even if they are in different locations. For example, 6:00 +0200 CEST and 4:00 UTC are Equal. See the documentation on the Time type for the pitfalls of using == with Time values; most code should use Equal instead.

    Example

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        secondsEastOfUTC := int((8 * time.Hour).Seconds())
        beijing := time.FixedZone("Beijing Time", secondsEastOfUTC)
    
        // Unlike the equal operator, Equal is aware that d1 and d2 are the
        // same instant but in different time zones.
        d1 := time.Date(2000, 2, 1, 12, 30, 0, 0, time.UTC)
        d2 := time.Date(2000, 2, 1, 20, 30, 0, 0, beijing)
    
        datesEqualUsingEqualOperator := d1 == d2
        datesEqualUsingFunction := d1.Equal(d2)
    
        fmt.Printf("datesEqualUsingEqualOperator = %v\n", datesEqualUsingEqualOperator)
        fmt.Printf("datesEqualUsingFunction = %v\n", datesEqualUsingFunction)
    
    }
    

    datesEqualUsingEqualOperator = false

    datesEqualUsingFunction = true

    resources

    • Time type documentation
    • Equal method documentation
    • time.Date

提交回复
热议问题