首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将unix时间戳解析为time.Time

如何将unix时间戳解析为time.Time
EN

Stack Overflow用户
提问于 2014-07-28 08:45:59
回答 3查看 217.2K关注 0票数 172

我正在尝试解析Unix的timestamp,但是我遇到了超出范围的错误。这对我来说没有什么意义,因为布局是正确的(就像在Go文档中一样):

代码语言:javascript
复制
package main

import "fmt"
import "time"

func main() {
    tm, err := time.Parse("1136239445", "1405544146")
    if err != nil{
        panic(err)
    }

    fmt.Println(tm)
}

Playground

EN

回答 3

Stack Overflow用户

发布于 2017-12-06 16:59:21

您可以直接使用时间的time.Unix函数,该函数将unix时间戳转换为UTC。

代码语言:javascript
复制
package main

import (
  "fmt"
  "time"
)


func main() {
    unixTimeUTC:=time.Unix(1405544146, 0) //gives unix time stamp in utc 

    unitTimeInRFC3339 :=unixTimeUTC.Format(time.RFC3339) // converts utc time to RFC3339 format

    fmt.Println("unix time stamp in UTC :--->",unixTimeUTC)
    fmt.Println("unix time stamp in unitTimeInRFC3339 format :->",unitTimeInRFC3339)
}

输出

代码语言:javascript
复制
unix time stamp in UTC :---> 2014-07-16 20:55:46 +0000 UTC
unix time stamp in unitTimeInRFC3339 format :----> 2014-07-16T20:55:46Z

签到Go游乐场:https://play.golang.org/p/5FtRdnkxAd

票数 19
EN

Stack Overflow用户

发布于 2017-12-14 11:47:29

分享我为dates创建的几个函数:

请注意,我想获得特定位置的时间(不仅仅是UTC时间)。如果您需要UTC时间,只需删除锁定变量和.In(锁定)函数调用。

代码语言:javascript
复制
func GetTimeStamp() string {
     loc, _ := time.LoadLocation("America/Los_Angeles")
     t := time.Now().In(loc)
     return t.Format("20060102150405")
}
func GetTodaysDate() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02")
}

func GetTodaysDateTime() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("2006-01-02 15:04:05")
}

func GetTodaysDateTimeFormatted() string {
    loc, _ := time.LoadLocation("America/Los_Angeles")
    current_time := time.Now().In(loc)
    return current_time.Format("Jan 2, 2006 at 3:04 PM")
}

func GetTimeStampFromDate(dtformat string) string {
    form := "Jan 2, 2006 at 3:04 PM"
    t2, _ := time.Parse(form, dtformat)
    return t2.Format("20060102150405")
}
票数 6
EN

Stack Overflow用户

发布于 2020-07-24 01:45:21

我在时间戳为float64的地方做了大量日志记录,并使用此函数获取字符串形式的时间戳:

代码语言:javascript
复制
func dateFormat(layout string, d float64) string{
    intTime := int64(d)
    t := time.Unix(intTime, 0)
    if layout == "" {
        layout = "2006-01-02 15:04:05"
    }
    return t.Format(layout)
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24987131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档