How to check whether current local time is DST?

前端 未结 3 1469
孤独总比滥情好
孤独总比滥情好 2021-01-04 12:29

In Ruby, for example, there\'s the Time#dst? function, which returns true in the case it is daylight saving time. Is there a Go standard library API call to do

3条回答
  •  Happy的楠姐
    2021-01-04 13:00

    You can infer the result. For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // isTimeDST returns true if time t occurs within daylight saving time
    // for its time zone.
    func isTimeDST(t time.Time) bool {
        // If the most recent (within the last year) clock change
        // was forward then assume the change was from std to dst.
        hh, mm, _ := t.UTC().Clock()
        tClock := hh*60 + mm
        for m := -1; m > -12; m-- {
            // assume dst lasts for least one month
            hh, mm, _ := t.AddDate(0, m, 0).UTC().Clock()
            clock := hh*60 + mm
            if clock != tClock {
                if clock > tClock {
                    // std to dst
                    return true
                }
                // dst to std
                return false
            }
        }
        // assume no dst
        return false
    }
    
    func main() {
        pstLoc, err := time.LoadLocation("America/Los_Angeles")
        if err != nil {
            fmt.Println(err)
            return
        }
    
        utc := time.Date(2018, 10, 29, 14, 0, 0, 0, time.UTC)
        fmt.Println(utc, utc.Location(), ": DST", isTimeDST(utc))
        local := utc.In(time.Local)
        fmt.Println(local, local.Location(), ": DST", isTimeDST(local))
        pst := utc.In(pstLoc)
        fmt.Println(pst, pst.Location(), ": DST", isTimeDST(pst))
    
        utc = utc.AddDate(0, 3, 0)
        fmt.Println(utc, utc.Location(), ": DST", isTimeDST(utc))
        local = utc.In(time.Local)
        fmt.Println(local, local.Location(), ": DST", isTimeDST(local))
        pst = utc.In(pstLoc)
        fmt.Println(pst, pst.Location(), ": DST", isTimeDST(pst))
    }
    

    Output:

    2018-10-29 14:00:00 +0000 UTC UTC : DST false
    2018-10-29 10:00:00 -0400 EDT Local : DST true
    2018-10-29 07:00:00 -0700 PDT America/Los_Angeles : DST true
    2019-01-29 14:00:00 +0000 UTC UTC : DST false
    2019-01-29 09:00:00 -0500 EST Local : DST false
    2019-01-29 06:00:00 -0800 PST America/Los_Angeles : DST false
    

提交回复
热议问题