【问题标题】:How to construct time.Time with timezone offset [duplicate]如何使用时区偏移构造 time.Time [重复]
【发布时间】:2019-06-30 07:35:23
【问题描述】:

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

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

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

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

这是我目前所拥有的:

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

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

【问题讨论】:

    标签: go time timezone timezone-offset


    【解决方案1】:

    您可以使用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
    

    【讨论】:

    • 有什么好办法把-0800转换成-8*3600
    • 所以-0700 是任意的,因为它只是一个格式说明符?这可能是任何有效的时区吗?
    • @jftuga 必须使用参考时间给出布局(格式),即Mon Jan 2 15:04:05 -0700 MST 2006。因此,布局中的区域偏移量必须为 -7 小时,并以您输入的方式格式化。这在time.Parse()中有详细说明。
    猜你喜欢
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2015-11-12
    • 2012-05-23
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2014-07-19
    相关资源
    最近更新 更多