Setting timezone globally in golang

后端 未结 3 507
北恋
北恋 2021-01-04 20:46

I\'m trying to modify golang timezone for my application

I have took a look at time package, initializing timezone happens in

<
3条回答
  •  借酒劲吻你
    2021-01-04 21:13

    I may be late but setting timezone in a global env is not a reliable approach. It should be set globally in a variable or in a struct. The below is an example of timezone set in a variable. Also in Go Playground

    package main
    
    import (
        "fmt"
        "log"
        "time"
    )
    
    func main() {
        if err := setTimezone("America/Los_Angeles"); err != nil {
            log.Fatal(err) // most likely timezone not loaded in Docker OS
        }
        t := getTime(time.Now())
        fmt.Println(t)
    }
    
    var loc *time.Location
    
    func setTimezone(tz string) error {
        location, err := time.LoadLocation("America/Los_Angeles")
        if err != nil {
            return err
        }
        loc = location
        return nil
    }
    
    func getTime(t time.Time) time.Time {
        return t.In(loc)
    }
    

提交回复
热议问题