在Golang中获取完整的UTC偏移量格式

I need to get the UTC offset for a location. I am getting trouble with the inconsistency of the results from different values. All I need to get are values in the format +HHMM (e.g., +0100 for "Europe/Rome").

func main() {
    loc, _:= time.LoadLocation("Asia/Kathmandu")
    offset, others:= time.Now().In(loc).Zone()
    fmt.Println(offset, others)
}

Playground

What I get:

  • "Asia/Kathmandu": +0545 (suitable)
  • "Asia/Ho_Chi_Minh": +07 (should be +0700)
  • "America/Phoenix": MST (should be -0700)
  • "Europe/Rome": CET (should be +0100)

Reference Timezone country names

Please help me.

The Zone() method you're using is working exactly as advertized.

Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.

A better approach for you would be to use the Format method. Something like:

zone := time.Now().In(loc).Format("-0700")

Of course, be aware: Even this won't be 100% consistent, due to daylight savings time.