Golang time.parse() function is used to “parse a formatted string and returns the time value represented by the string“.
Syntax
func Parse(layout, value string) (Time, error)
Parameters
- layout: It is a layout string specifying the input string’s format.
- value: The input string represents the date and time you want to parse.
Return value
The Parse() function returns the time value that it represents. And if a time zone indicator is absent, it returns a time in UTC.
Example 1: How to Use time.Parse() function
package main
import (
"fmt"
"time"
)
const (
layout = "2006-01-02 15:04:05"
)
func main() {
dt := "2022-12-13 14:15:16"
tm, err := time.Parse(layout, dt)
if err != nil {
fmt.Println(err)
}
fmt.Println(tm)
}
Output
2022-12-13 14:15:16 +0000 UTC
In the above code, the time.Parse() function is used to parse a string representing a date and time in the format “YYYY-MM-DD HH:MM:SS”. The resulting time.Time value is then printed to the console.
Example 2: Golang Error: Month out of range
The time string is the string representation of the time value to be parsed. It should match the format specified by the layout string.
If the time string is in the correct format, time.Parse will return a time.Time value representing the parsed time.
If the time string is not in the correct format, time.Parse will return an error.
package main
import (
"fmt"
"time"
)
const (
layout = "2006-01-02 14:04:05"
)
func main() {
dt := "2022-12-13 14:15:16"
tm, err := time.Parse(layout, dt)
if err != nil {
fmt.Println(err)
}
fmt.Println(tm)
}
Output
parsing time "2022-12-13 14:15:16": month out of range
0001-01-01 00:00:00 +0000 UTC
That’s it.
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
I don’t understand – Why?!!
With this: layout = “2006-01-02 14:04:05” – OK
and with this: layout = “2006-01-02 15:04:05” – Error
Answer here (russian language) – https://www.linux.org.ru/forum/development/17265969