如何将日期时间格式化为显示IANA格式的时区?

huangapple go评论134阅读模式
英文:

How to format a date-time to display the timezone in IANA format?

问题

以下是代码的翻译结果:

fmt.Println(time.Now().Format("2 Jan 2006 03:04:05PM Europe/London"))

输出结果为:

26 Nov 2021 04:00:31PM Europe/London
英文:

The following code

fmt.Println(time.Now().Format("2 Jan 2006 03:04:05PM MST"))

prints

26 Nov 2021 04:00:31PM GMT

How to format the timezone as Europe/London i.e. in the IANA format? The expected output is

26 Nov 2021 04:00:31PM Europe/London

答案1

得分: 3

直接使用time格式布局无法直接实现此操作。

但是Location.String通常会打印出IANA名称。

> String返回与LoadLocation或FixedZone的name参数对应的时区信息的描述性名称。

LoadLocation通常以IANA字符串作为输入:

> 如果name是""或"UTC",LoadLocation返回UTC。如果name是"Local",LoadLocation返回Local。
>
> 否则,name被视为与IANA时区数据库中的文件对应的位置名称,例如"America/New_York"。

现在,"Local"不是一个有效的IANA名称,但"UTC"是有效的 - 实际上,UTCEtc/UTC的别名。

time包的另一个注意事项是,Location.String将打印传递给FixedZone的名称,而这可以是任何内容。

因此,如果您能够对time.Location的实例化方式做出假设,以下可能是一个可行的解决方案:

fmt.Printf("%s %s", t.Format("2 Jan 2006 03:04:05PM"), t.Location())

否则,您将不得不使用一些第三方包,或者自己编写映射。

英文:

There isn't an option to do this directly with the time format layout.

However Location.String will print the IANA name in most cases.

> String returns a descriptive name for the time zone information, corresponding to the name argument to LoadLocation or FixedZone.

And LoadLocation usually takes the IANA string as input:

> If the name is "" or "UTC", LoadLocation returns UTC. If the name is "Local", LoadLocation returns Local.
>
> Otherwise, the name is taken to be a location name corresponding to a file in the IANA Time Zone database, such as "America/New_York".

Now "Local" isn't a valid IANA name, but "UTC" is — well, actually UTC is an alias of Etc/UTC.

The other gotcha with the std time package is that Location.String will print the name passed to FixedZone, and that can be literally anything.

So, if you are able to make assumptions about how your time.Location are instantiated, the following might be a viable solution:

fmt.Printf("%s %s", t.Format("2 Jan 2006 03:04:05PM"), t.Location())

Otherwise you will have to use some third-party package, or roll out your own mapping.

huangapple
  • 本文由 发表于 2021年11月27日 00:12:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/70127235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定