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):
package main
import "fmt"
import "time"
func main() {
tm, err := time.Parse("1136239445", "1405544146")
if err != nil{
panic(err)
}
fmt.Println(tm)
}
Playground
We can do this by simply multiplying the Unix timestamp by 1000 . Unix time is the number of seconds that have elapsed since the Unix epoch, which is the time 00:00:00 UTC on 1 January 1970 .
To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With