Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a MySQL datetime string to time.Time format

Tags:

datetime

time

go

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()
like image 676
Roy van Zanten Avatar asked Dec 23 '15 15:12

Roy van Zanten


1 Answers

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.

like image 122
del-boy Avatar answered Oct 16 '22 06:10

del-boy