Convert CST DateTime to Unix timestamp in Golang

Viewed 52

I have a datetime format 0000-00-00 00:00:00 in China Standard Time, I want to convert it to unix timestamp in Golang.

I am not sure what default timestamp we need, if we call time.Unix( ) directly.

1 Answers

just use time.Location

func main() {
    now := "2022-08-11 11:40:00"
    location, err := time.LoadLocation("Asia/Shanghai")
    if err != nil {
        log.Fatalln(err)
    }
    t, err := time.ParseInLocation("2006-01-02 15:04:05", now, location)
    if err != nil {
        log.Fatalln(err)
    }
    //2022-08-11 11:40:00 +0800 CST
    fmt.Println(t)
    //1660189200
    fmt.Println(t.Unix())
}

Related