英文:
Unix timestamp format conversion
问题
一个unix_timestamp为1405936049
对应的是:2014-07-21 09:47:29
。我的目标是从时间戳中得到后者的形式。
在阅读格式文档后,我得到了以下代码:
fmt.Println(time.Unix(1405936049, 0).Format("2006-01-02 15:04:05"))
这将输出:2014-07-21 02:47:29
,这是有道理的,因为time.Unix(1405936049, 0)
的结果是:2014-07-21 02:47:29 -0700 PDT
(明确一下,我想要的是2014-07-21 09:47:29,小时不正确)。
我相信如果我知道正确的术语,我就能在文档中找到解决方案,但目前我不确定如何告诉解析器考虑-0700
,或者也许可以使用time.Unix()
之外的其他方法,这样得到的时间就已经考虑了小时差异?任何帮助将不胜感激。
英文:
A unix_timestamp of 1405936049
corresponds to: 2014-07-21 09:47:29
. My goal is to derive the latter form from the timestamp.
After reading the format documentation, I came up with the following:
fmt.Println(time.Unix(1405936049, 0).Format("2006-01-02 15:04:05"))
which yields: 2014-07-21 02:47:29
, which makes sense, since time.Unix(1405936049, 0)
gives: 2014-07-21 02:47:29 -0700 PDT
(to be clear, I want: 2014-07-21 09:47:29, the hour is incorrect).
I'm sure if I knew the correct terminology, I'd be able to find a solution in the documentation, but at this point, I'm uncertain how to tell the parser to account for -0700
or perhaps an alternative solution would be to use something besides time.Unix()
, so that the resulting time would have already accounted for the hour difference? Any help would be appreciated.
答案1
得分: 3
你想要获取UTC时间,而不是你本地的PDT时间。例如,
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Unix(1405936049, 0).UTC().Format("2006-01-02 15:04:05"))
}
输出结果为:
2014-07-21 09:47:29
英文:
You want the UTC time, not your local PDT time. For example,
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Unix(1405936049, 0).UTC().Format("2006-01-02 15:04:05"))
}
Output:
2014-07-21 09:47:29
答案2
得分: 0
你需要使用Location
来实现这个功能:
loc, _ := time.LoadLocation("Europe/Paris")
fmt.Println(time.Unix(1405936049, 0).In(loc).Format("2006-01-02 15:04:05"))
我认为你想要的时区是"UTC",但是我建议你自己确认一下(否则,这里有所有可用时区的列表)。在playground中时间格式已经是09:47:29
是因为playground不包含时区信息,默认使用的是UTC。
英文:
You have to use Location
for this:
loc, _ := time.LoadLocation("Europe/Paris")
fmt.Println(time.Unix(1405936049, 0).In(loc).Format("2006-01-02 15:04:05"))
I think the location you want is "UTC", but I let you check (otherwise, here is a list of all available locations). The reason why in playground the format is already 09:47:29
is that playground does not include locations and uses UTC by default.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论