如何将 unix 时间戳解析为 time.Time [英] How to parse unix timestamp to time.Time

查看:36
本文介绍了如何将 unix 时间戳解析为 time.Time的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析 Unix timestamp,但出现超出范围的错误.这对我来说没有意义,因为布局是正确的(如 Go 文档中所示):

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

游乐场

推荐答案

time.Parse 函数不处理 Unix 时间戳.相反,您可以使用 strconv.ParseInt 将字符串解析为 int64 并使用 time.Unix 创建时间戳:

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

输出:

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

游乐场: http://play.golang.org/p/v_j6UIro7a

strconv.Atoi 更改为 strconv.ParseInt 以避免 int 在 32 位系统上溢出.

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

这篇关于如何将 unix 时间戳解析为 time.Time的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆