英文:
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"
是有效的 - 实际上,UTC
是Etc/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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论