How to parse unix timestamp to time.Time

后端 未结 6 2039
悲&欢浪女
悲&欢浪女 2020-12-02 05:27

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):



        
6条回答
  •  春和景丽
    2020-12-02 06:28

    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.

提交回复
热议问题