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)
}
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
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)
}
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!
from https://ift.tt/T3jsBnz
0 Comments