如何构建 time.Time with timezone offset

这是来自 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在这里不合适。


aluckdog
浏览 79回答 1
1回答

MMTTMM

您可以用来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
打开App,查看更多内容
随时随地看视频慕课网APP