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?

>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")
}

Leave a Reply