这是Apache日志的示例日期:
[07/Mar/2004:16:47:46 -0800]
我已成功将其解析为year(int),month(time.Month),day(int),hour(int),minute(int),second(int)和timezone(string)。
我如何构建time.Time,使其包含-0800
时区偏移量?
这是我到目前为止:
var nativeDate time.Time
nativeDate = time.Date(year, time.Month(month), day, hour, minute, second, 0, ????)
我应该用什么代替????
? time.Local
或time.UTC
不适合这里。
您可以使用time.FixedZone()
构造具有固定偏移的time.Location
。
例:
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