How to parse unix timestamp to time.Time

后端 未结 6 2040
悲&欢浪女
悲&欢浪女 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:10

    According to the go documentation, Unix returns a local time.

    Unix returns the local Time corresponding to the given Unix time

    This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

    To do so, I adapted the snippet to make it return a time in UTC:

    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm.UTC())
    

    This prints on my machine (in CEST)

    2014-07-16 20:55:46 +0000 UTC
    

提交回复
热议问题