亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何構建 time.Time with timezone offset

如何構建 time.Time with timezone offset

Go
aluckdog 2023-06-05 17:25:26
這是來自 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


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號