我试图解析一个Unix时间戳,但我得到了超出范围的错误。这对我来说没有意义,因为布局是正确的(就像在Go文档中一样):
package main
import "fmt"
import "time"
func main() {
tm, err := time.Parse("1136239445", "1405544146")
if err != nil{
panic(err)
}
fmt.Println(tm)
}
操场上
我试图解析一个Unix时间戳,但我得到了超出范围的错误。这对我来说没有意义,因为布局是正确的(就像在Go文档中一样):
package main
import "fmt"
import "time"
func main() {
tm, err := time.Parse("1136239445", "1405544146")
if err != nil{
panic(err)
}
fmt.Println(tm)
}
操场上
当前回答
根据go文档,Unix返回一个本地时间。
Unix返回与给定的Unix时间对应的本地时间
这意味着输出将取决于运行代码的机器,这通常是您所需要的,但有时,您可能希望使用UTC格式的值。
为此,我调整了代码片段,使其返回UTC时间:
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())
在我的机器上打印(CEST)
2014-07-16 20:55:46 +0000 UTC
其他回答
你可以直接利用时间。Unix时间函数,将Unix时间戳转换为UTC时间戳
package main
import (
"fmt"
"time"
)
func main() {
unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc
unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format
fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}
输出
unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z
Check in Go Playground: https://play.golang.org/p/5FtRdnkxAd
对于millis Unix时间戳精度,在go1.18中
i, err := strconv.ParseInt("1652084489543", 10, 64)
if err != nil {
panic(err)
}
tm := time.UnixMilli(i)
fmt.Println(tm)
分享一些我为日期创建的函数:
请注意,我想获取特定位置的时间(而不仅仅是UTC时间)。如果你想要UTC时间,只需删除loc变量和. in (loc)函数调用。
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
我做了很多日志记录,其中时间戳是float64,并使用这个函数来获取时间戳作为字符串:
func dateFormat(layout string, d float64) string{
intTime := int64(d)
t := time.Unix(intTime, 0)
if layout == "" {
layout = "2006-01-02 15:04:05"
}
return t.Format(layout)
}
根据go文档,Unix返回一个本地时间。
Unix返回与给定的Unix时间对应的本地时间
这意味着输出将取决于运行代码的机器,这通常是您所需要的,但有时,您可能希望使用UTC格式的值。
为此,我调整了代码片段,使其返回UTC时间:
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())
在我的机器上打印(CEST)
2014-07-16 20:55:46 +0000 UTC