如何用时区偏移构造 time.Time
How to construct time.Time with timezone offset
这是来自 Apache 日志的示例日期:
[07/Mar/2004:16:47:46 -0800]
我已成功将其解析为年(整数)、月(time.Month)、日(整数)、小时(整数)、分钟(整数)、秒(整数)和时区(字符串) .
如何构造 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()
to construct a 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
这是来自 Apache 日志的示例日期:
[07/Mar/2004:16:47:46 -0800]
我已成功将其解析为年(整数)、月(time.Month)、日(整数)、小时(整数)、分钟(整数)、秒(整数)和时区(字符串) .
如何构造 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()
to construct a 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