Tejas 07
Tejas 07

Reputation: 79

Golang : converting yyyy:MM:dd hr:mm:ss i.e I am getting date in string and the same date need to be parse to save in mysql db

layout := "2006-01-02 15:04:05"
    str := "2018-10-11 13:10:47"
    t, err := time.Parse(layout, str)

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

I am getting output as 2018-10-11 13:10:47 +0000 UTC, but I want to store in mysql db as 2018-10-11 13:10:47. How do I parse exactly for mysql datetime?

Upvotes: 0

Views: 8465

Answers (2)

Adrian
Adrian

Reputation: 2113

How about useing DateFormatToLayout("yyyy-MM-dd hh:mm:ss") utility method to convert ISO date style to time layout

package main

import (
    "fmt"
    "github.com/viant/toolbox"
    "time"
)

func main() {
    timeLayout := toolbox.DateFormatToLayout("yyyy-MM-dd hh:mm:ss")
    fmt.Printf("%s\n", time.Now().Format(timeLayout))
}

Time Utils

Upvotes: 1

peterSO
peterSO

Reputation: 166795

layout := "2006-01-02 15:04:05"
fmt.Println(t.Format(layout))

Output:

2018-10-11 13:10:47

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02 15:04:05"
    str := "2018-10-11 13:10:47"
    t, err := time.Parse(layout, str)

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

Playground: https://play.golang.org/p/NuloBCXBdhH

Output:

2018-10-11 13:10:47 +0000 UTC
2018-10-11 13:10:47

Upvotes: 7

Related Questions