How to properly use time.Parse to create a time object from a Unix time string?

huangapple go评论77阅读模式
英文:

How to properly use time.Parse to create a time object from a Unix time string?

问题

我们正在尝试将一个作为字符串提供的Unix时间戳解析为时间对象,但是以下代码无法正常工作:

package main

import (
	"fmt"
	"time"
)

func main() {
	t, _ := time.Parse(time.UnixDate, "1393344464")
	fmt.Printf("%v", t)
}

它一直返回0001-01-01 00:00:00 +0000 UTCGo Playground.

英文:

We are trying to parse a unix timestamp, which is available as a string, into a time object, however, the following does not work:

package main

import (
"fmt"
"time"
)

func main() {
	t, _ := time.Parse(time.UnixDate, "1393344464")
	fmt.Printf("%v", t)
}

It keeps returning 0001-01-01 00:00:00 +0000 UTC. Go Playground.

答案1

得分: 5

前言 - 永远不要忽略error(t, _ :=),否则你会错过关键的错误信息,并且会一直感到困惑。

关于你的问题 - 你需要使用time.Unix来实现你想要的功能。

package main

import (
  "log"
  "time"
)

func main() {
  t, err := time.Parse(time.UnixDate, "1393344464")
  if err != nil {
    log.Println(err)
  }
  log.Printf("%v\n", t)

  t = time.Unix(1393344464,0)
  log.Printf("%v\n", t)
}

[1]: http://golang.org/pkg/time/#Unix
英文:

Preface — never ignore the error (t, _ :=), you'll miss the critical error message and be confused all the time.

About you problem — you need to use time.Unix to achieve what you want.

package main

import (
  "log"
  "time"
)

func main() {
  t, err := time.Parse(time.UnixDate, "1393344464")
  if err != nil {
    log.Println(err)
  }
  log.Printf("%v\n", t)

  t = time.Unix(1393344464,0)
  log.Printf("%v\n", t)
}

答案2

得分: 5

首先,你有一个错误,并且没有进行错误检查:http://play.golang.org/p/7ruFfv5QHT 这是一个不好的做法(这些错误对于调试是有帮助的!:) 使用它们!)

UnixDate用于Unix日期的字符串表示,而不是时间戳。根据源代码:UnixDate = "Mon Jan _2 15:04:05 MST 2006"

使用time.Unix

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Unix(1393324260, 0)
    fmt.Printf("%v", t)
}

http://play.golang.org/p/gj_4EtiOVY

英文:

First of all, you have an error and you're not checking it: http://play.golang.org/p/7ruFfv5QHT which is bad practice (these errors are helpful for debugging! How to properly use time.Parse to create a time object from a Unix time string? use them!)

UnixDate is for unix string representations of dates; not timestamps. From the source: UnixDate = "Mon Jan _2 15:04:05 MST 2006".

Use time.Unix:

package main

import (
    "fmt"
    "time"
)

func main() {
	t := time.Unix(1393324260, 0)
	fmt.Printf("%v", t)
}

http://play.golang.org/p/gj_4EtiOVY

huangapple
  • 本文由 发表于 2014年2月26日 00:15:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/22019926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定