我需要在不同的时区获得当前时间.
目前我知道我们可以做到以下几点:
t := time.Now()
fmt.Println("Location:", t.Location(), ":Time:", t)
utc, err := time.LoadLocation("America/New_York")
if err != nil {
fmt.Println("err: ", err.Error())
}
fmt.Println("Location:", utc, ":Time:", t.In(utc))
Run Code Online (Sandbox Code Playgroud)
LoadLocation名称将被视为与IANA时区数据库中的文件对应的位置名称,例如"America/New_York".
有没有更简单的方法来获得当前时间,如果国家名称或GMT抵消给出例如印度的+530?
编辑:我也想支持Day light节省.
小智 45
//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")
//set timezone,
now := time.Now().In(loc)
Run Code Online (Sandbox Code Playgroud)
我喜欢这样
//init the loc
loc, _ := time.LoadLocation("Asia/Shanghai")
//set timezone,
now := time.Now().In(loc)
Run Code Online (Sandbox Code Playgroud)
在哪里可以找到该地点的名称?
您可以在zoneinfo.zip上看到它
一些例子
package _test
import (
"fmt"
"testing"
"time"
)
func TestTime(t *testing.T) {
myT := time.Date(2022, 4, 28, 14, 0, 0, 0, time.UTC)
for _, d := range []struct {
name string
expected string
}{
{"UTC", "2022-04-28 14:00:00 +0000 UTC"},
{"America/Los_Angeles", "2022-04-28 07:00:00 -0700 PDT"},
{"Asia/Tokyo", "2022-04-28 23:00:00 +0900 JST"},
{"Asia/Taipei", "2022-04-28 22:00:00 +0800 CST"},
{"Asia/Hong_Kong", "2022-04-28 22:00:00 +0800 HKT"},
{"Asia/Shanghai", "2022-04-28 22:00:00 +0800 CST"},
} {
loc, _ := time.LoadLocation(d.name)
if val := fmt.Sprintf("%s", myT.In(loc)); val != d.expected {
fmt.Println(val)
t.FailNow()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37262 次 |
| 最近记录: |