snippetgoCritical
How to parse unix timestamp to time.Time
Viewed 0 times
howtimestampparsetimeunix
Problem
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 Go docs):
Playground
package main
import "fmt"
import "time"
func main() {
tm, err := time.Parse("1136239445", "1405544146")
if err != nil{
panic(err)
}
fmt.Println(tm)
}Playground
Solution
The
Output:
Playground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from
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 UTCPlayground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from
strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.Code Snippets
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 UTCContext
Stack Overflow Q#24987131, score: 423
Revisions (0)
No revisions yet.