为了账号安全,请及时绑定邮箱和手机立即绑定

如何构建 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 关注
  • 77 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信