Reputation: 3415
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()
Upvotes: 5
Views: 6743
Reputation: 3654
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.
Upvotes: 15
Reputation: 11480
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!
Upvotes: 1