1

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.

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.