Ralf
Ralf

Reputation: 2652

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

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.

Upvotes: 1

Views: 180

Answers (2)

weberc2
weberc2

Reputation: 7958

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

Upvotes: 5

Kavu
Kavu

Reputation: 8394

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

Upvotes: 5

Related Questions