The Parse() function allows you to parse a formatted date string and return the time value represented by the string.

The function syntax is as shown:

func Parse(layout, value string) (Time, error)

The function takes a layout and a formatted date format as the parameters. It then returns the time value.

Keep in mind that Go does not use the yyyy-mm-dd layout to format time. Instead, it uses the value:

 Mon Jan 2 15:04:05 MST 2006

Consider the example below that illustrates how to use the parse function.

package main


import (


    “fmt”


    “time”

)


const (


    layout = “2006-01-02”

)


func main() {


    date := “2022-02-01”


    time, _ := time.Parse(layout, date)


    fmt.Println(time)

}

The code above will parse the provided date and return the time as shown in the output below:

$ go run parse.go

2022-02-01 00:00:00 0000 UTC

You can also specify another layout format as shown:

package main


import (


    “fmt”


    “time”

)


const (


    layout = “Jan 2, 2006 at 3:04pm (MST)”

)


func main() {


    date := “Feb 1, 2022 at 12:59pm (PST)”


    kitchen, _ := time.Parse(layout, date)


    fmt.Println(kitchen)

}

The code above should return an output as:

2022-02-01 12:59:00 0000 PST

The Parse method uses example-based layouts. In most cases, you can use the layouts defined in the time package. You can also create custom-based layouts. Ensure they reference the time:

Mon Jan 2 15:04:05 MST 2006

Thanks for reading!

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352b73501d.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list