Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang: extract time from datetime string

I am trying to extract the time from a datetime string in golang, here is what I have:

func GetTimeStr(d string) string {
    layout := "2014-09-12T11:45:26"
    d = d[:len(layout)]
    t, _ := time.Parse(layout, d)
    return t.Format("15:04:05")
}

My input look like this:

2022-09-23T16:28:19.846821Z

However I am getting 00:00:00, what am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your layout string is wrong. Try changing it:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(GetTimeStr("2022-09-23T16:28:19.846821Z"))
}
func GetTimeStr(d string) string {
    layout := "2006-01-02T15:04:05"
    d = d[:len(layout)]
    t, _ := time.Parse(layout, d)
    return t.Format("15:04:05")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading