可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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) }
play
回答1:
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) }
Output:
2014-07-16 20:55:46 +0000 UTC
Playground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from strconv.Atoi
to strconv.ParseInt
to avoid int overflows on 32 bit systems.
回答2:
you can directly use time.Unix function of time which converts the unix time stamp to 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)
}
Output
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
回答3:
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
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") }
回答4:
Just use time.Parse
example:
package main import ( "fmt" "time" ) func main() { fromString := "Wed, 6 Sep 2017 10:43:01 +0300" t, e := time.Parse("Mon, _2 Jan 2006 15:04:05 -0700", fromString) if e != nil { fmt.Printf("err: %s\n", e) } fmt.Printf("UTC time: %v\n", t.UTC()) }
Working example on play.golang.org.