The function syntax is as shown:
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:
Consider the example below that illustrates how to use the parse function.
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:
2022-02-01 00:00:00 +0000 UTC
You can also specify another layout format as shown:
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:
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:
Thanks for reading!