這是來自 Apache 日志的示例日期:[07/Mar/2004:16:47:46 -0800]我已經成功地將其解析為年(int)、月(time.Month)、日(int)、小時(int)、分鐘(int)、秒(int)和時區(string)。我如何構建 time.Time 使其包含-0800時區偏移量?這是我到目前為止所擁有的:var nativeDate time.Time
nativeDate = time.Date(year, time.Month(month), day, hour, minute, second, 0, ????)我應該用什么代替?????time.Local或者time.UTC在這里不合適。
1 回答

MMTTMM
TA貢獻1869條經驗 獲得超4個贊
您可以用來time.FixedZone()
構造time.Location
具有固定偏移量的 a 。
例子:
loc := time.FixedZone("myzone", -8*3600)
nativeDate := time.Date(2019, 2, 6, 0, 0, 0, 0, loc)
fmt.Println(nativeDate)
輸出(在Go Playground上嘗試):
2019-02-06?00:00:00?-0800?myzone
如果您將區域偏移量作為字符串,則可以使用time.Parse()
它來解析它。使用僅包含參考區域偏移量的布局字符串:
t,?err?:=?time.Parse("-0700",?"-0800") fmt.Println(t,?err)
此輸出(在Go Playground上嘗試):
0000-01-01?00:00:00?-0800?-0800?<nil>
如您所見,結果的時time.Time
區偏移量為 -0800 小時。
所以我們原來的例子也可以寫成:
t, err := time.Parse("-0700", "-0800")
if err != nil {
? ? panic(err)
}
nativeDate := time.Date(2019, 2, 6, 0, 0, 0, 0, t.Location())
fmt.Println(nativeDate)
輸出(在Go Playground上嘗試):
2019-02-06?00:00:00?-0800?-0800
- 1 回答
- 0 關注
- 127 瀏覽
添加回答
舉報
0/150
提交
取消