5

I just cant manage to parse an SQL datetime (MySQL) value into a time.Time value. I cant find the layout fitting sql datetime. And also not really understand how this works.

I do imagine I'am not the first struggling with this, though i cant really find how I should make this work.

Input:

2015-12-23 00:00:00

Desired output:

1450825200

Code

time, err := time.Parse(time.SomeSqlDateTimeLayout, "2015-12-23 00:00:00")
timestamp := time.Unix()
Roy van Zanten
  • 3,125
  • 2
  • 17
  • 12
  • Do you just want to convert the string to a timestamp or do you want it to come out of the database as a `time.Time` value? I think the latter would be more useful. – jcbwlkr Dec 23 '15 at 15:31
  • Roy, you should not put the information from tags into title. You've tagged your question `go` and that's all what's needed. – kostix Dec 23 '15 at 16:30
  • 1
    Possible duplicate of [Go - Parsing date/time strings which are not 'standard' formats](http://stackoverflow.com/questions/14106541/go-parsing-date-time-strings-which-are-not-standard-formats) – Ezequiel Moreno Dec 24 '15 at 11:08

2 Answers2

14

You can create your own time format for parsing, if one does not exist in standard library.

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02 15:04:05"
    str := "2015-12-23 00:00:00"
    t, err := time.Parse(layout, str)

    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t.Unix())
}

Output

1450828800

I do not know were official documentation for time format is, but you can find it here, from line 64.

del-boy
  • 3,556
  • 3
  • 26
  • 39
2

Indeed, I'm not aware of any ISO-8601 parsing support in Go's standard libraries.

Let us use RFC-3309, which is the closest:

package main

import (
  "fmt"
  "time"
  "strings"
)

func main() {

  // convert iso-8601 into rfc-3339 format
  rfc3339t := strings.Replace("2015-12-23 00:00:00", " ", "T", 1) + "Z"

  // parse rfc-3339 datetime
  t, err := time.Parse(time.RFC3339, rfc3339t)
  if err != nil {
    panic(err)
  }

  // convert into unix time
  ut := t.UnixNano() / int64(time.Millisecond)

  fmt.Println(ut)
}

Output

1450828800000

Playground: http://play.golang.org/p/HxZCpxmjvg

Hope this helps!

Lior Bar-On
  • 10,784
  • 5
  • 34
  • 46