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

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

问题描述

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

This is an example date from an Apache log:

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

我已成功将其解析为年(int)、月(time.Month)、日(int)、小时(int)、分钟(int)、秒(int)和时区(字符串).

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?

这是我目前所拥有的:

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)

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

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)

这个输出(在 Go Playground 上试试):

This outputs (try it on the Go Playground):

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)

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

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

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

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