如何正确解析时区代码 [英] How to properly parse timezone codes

查看:111
本文介绍了如何正确解析时区代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,无论您为parseAndPrint函数选择的时区如何,结果始终为"[日期] 05:00:00 +0000 UTC".此代码有什么问题?时间应根据您选择的时区而变化. (Go Playground服务器显然是在UTC时区配置的.)

In the example bellow the result is always "[date] 05:00:00 +0000 UTC" regardless the timezone you choose for the parseAndPrint function. What is wrong with this code? The time should change depending on the timezone you choose. (Go Playground servers are apparently configured in UTC timezone).

http://play.golang.org/p/wP207BWYEd

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    parseAndPrint(now, "BRT")
    parseAndPrint(now, "EDT")
    parseAndPrint(now, "UTC")
}

func parseAndPrint(now time.Time, timezone string) {
    test, err := time.Parse("15:04:05 MST", fmt.Sprintf("05:00:00 %s", timezone))
    if err != nil {
        fmt.Println(err)
        return
    }

    test = time.Date(
        now.Year(),
        now.Month(),
        now.Day(),
        test.Hour(),
        test.Minute(),
        test.Second(),
        test.Nanosecond(),
        test.Location(),
    )

    fmt.Println(test.UTC())
}

推荐答案

解析时间时,您正在解析当前位置,只要您期望的那样就可以,并且时区缩写为从您所在的位置知道.

When you Parse a time, you are parsing it in your current location, which is OK as long as that's what you're expecting, and the timezone abbreviation is known from within your location.

如果您可以放弃时区,那么将要处理的所有时间归一化为UTC都容易得多.

If you can forgo timezones, it's far easier to normalize all the times you're dealing with into UTC.

下一个最简单的方法是处理带有显式偏移量的所有内容,例如-05:00.

The next easiest is handling everything with explicit offsets, like -05:00.

如果要处理源自其他时区的时间,则需要使用time.Location.您可以使用time.LoadLocation从本地时区db加载位置",并使用time.ParseInLocation解析那里的时间.

If you want to deal with times originating in other timezones, you need to use time.Location. You can load Locations from the local timezone db with time.LoadLocation, and parse times there with time.ParseInLocation.

这篇关于如何正确解析时区代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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