英文:
How to convert UTC time to unix timestamp
问题
我正在寻找一种将UTC时间字符串转换为Unix时间戳的方法。
我有一个字符串变量 02/28/2016 10:03:46 PM
,需要将其转换为类似于 1456693426
的Unix时间戳。
你有任何想法如何实现吗?
英文:
I am looking for an option to convert UTC time string to unix timestamp.
The string variable I have is 02/28/2016 10:03:46 PM
and it needs to be converted to a unix timestamp like 1456693426
Any idea how to do that?
答案1
得分: 19
首先,Unix时间戳1456693426
在UTC时间中并不是10:03:46 PM
,而是9:03:46 PM
。
在time
包中,有一个名为Parse的函数,它需要一个布局参数来解析时间。布局参数是根据参考时间Mon Jan 2 15:04:05 -0700 MST 2006
构建的。所以在你的情况下,布局参数应该是01/02/2006 3:04:05 PM
。使用Parse函数后,你会得到一个time.Time
结构体,你可以调用Unix方法来获取Unix时间戳。
package main
import (
"fmt"
"time"
)
func main() {
layout := "01/02/2006 3:04:05 PM"
t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
if err != nil {
fmt.Println(err)
}
fmt.Println(t.Unix())
}
英文:
First of, the unix timestamp 1456693426
does not have the time 10:03:46 PM
but 9:03:46 PM
in UTC.
In the time
package there is the function Parse with expects a layout to parse the time. The layout is constructed from the reference time Mon Jan 2 15:04:05 -0700 MST 2006
. So in your case the layout would be 01/02/2006 3:04:05 PM
. After using Parse you get a time.Time
struct on which you can call Unix to receive the unix timestamp.
package main
import (
"fmt"
"time"
)
func main() {
layout := "01/02/2006 3:04:05 PM"
t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
if err != nil {
fmt.Println(err)
}
fmt.Println(t.Unix())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论