如何构造time.Time与时区偏移 [英] How to construct time.Time with timezone offset

查看:86
本文介绍了如何构造time.Time与时区偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是来自Apache日志的示例日期:

This is an example date from an Apache log:

[07/Mar/2004:16:47:46 -0800]

我已经成功地将其解析为year(int),month(time.Month),day(int),hour(int),minute(int),second(int)和timezone(string).

I have successfully parsed this into year(int), month(time.Month), day(int), hour(int), minute(int), second(int), and timezone(string).

如何构造time.Time,使其包含-0800时区偏移量?

How can I construct time.Time such that it includes the -0800 time zone offset?

这是我到目前为止所拥有的:

This is what I have so far:

var nativeDate time.Time
nativeDate = time.Date(year, time.Month(month), day, hour, minute, second, 0, ????)

我应该用什么代替????? time.Localtime.UTC在这里不合适.

What should I use in place of ????? time.Local or time.UTC is not appropriate here.

推荐答案

您可以使用 time.FixedZone() 以构造具有固定偏移量的 time.Location .

You may use time.FixedZone() to construct a time.Location with a fixed offset.

示例:

loc := time.FixedZone("myzone", -8*3600)
nativeDate := time.Date(2019, 2, 6, 0, 0, 0, 0, loc)
fmt.Println(nativeDate)

输出(在游乐场上尝试):

2019-02-06 00:00:00 -0800 myzone

如果区域偏移量为字符串,则可以使用 time.Parse() 解析它.使用仅包含参考区域偏移量的布局字符串:

If you have the zone offset as a string, you may use time.Parse() to parse it. Use a layout string that only contains the reference zone offset:

t, err := time.Parse("-0700", "-0800")
fmt.Println(t, err)

此输出(在游乐场上尝试):

0000-01-01 00:00:00 -0800 -0800 <nil>

如您所见,结果 time.Time 的区域偏移为- 0800小时.

As you can see, the result time.Time has a zone offset of -0800 hours.

所以我们的原始示例也可以写成:

So our original example can also be written as:

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)

输出(在游乐场上尝试):

2019-02-06 00:00:00 -0800 -0800

这篇关于如何构造time.Time与时区偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆