如何解析golang中的unix时间戳 [英] How to parse unix timestamp in golang
本文介绍了如何解析golang中的unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试解析Unix 时间戳,但我超出范围错误。这不是真的有意义,因为布局是正确的(如在golang文档):
I'm trying to parse an Unix timestamp but I get out of range error. That doesn't really makes sense to me because the layout is correct (as in the golang docs):
package main
import "fmt"
import "time"
func main() {
tm, err := time.Parse("1136239445", "1405544146")
if err !=nil{
panic(err)
}
fmt.Println(tm)
}
推荐答案
time.Parse
函数不执行Unix时间戳。相反,您可以使用 strconv.ParseInt
将字符串解析为 int64
,并使用创建时间戳time.Unix
:
The time.Parse
function does not do Unix timestamps. Instead you can use strconv.ParseInt
to parse the string to int64
and create the timestamp with time.Unix
:
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm)
}
输出:
2014-07-16 20:55:46 +0000 UTC
游乐场: http://play.golang。 org / p / v_j6UIro7a
编辑:
strconv.Atoi
到 strconv.ParseInt
,以避免32位系统上的int溢出。
Changed from strconv.Atoi
to strconv.ParseInt
to avoid int overflows on 32 bit systems.
这篇关于如何解析golang中的unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文