I need to convert a traditional American date, i.e "05/24/2024" to ISO date string i.e "20240524" in Go without painful string manipulation.
I tried this code:
func showISODate() {
dateStr := "05/24/2024" // date in 'String' data type
dateValue, err := time.Parse("20060102", dateStr) // convert 'String' to 'Time' data type
if err != nil {
log.Println(err.Error())
}
fmt.Println(dateValue) // output: 0001-01-01 00:00:00 +0000 UTC
dateStr = dateValue.Format("20060102") // output: 00010101
fmt.Println(dateStr)
}
This code fails: Output is zeroed out, with error message: parsing time "05/24/2024" as "20060102": cannot parse "05/24/2024" as "2006"
What am I doing wrong? How should I do this?
>Solution :
The layout you pass to time.Parse should match the input format:
func showISODate() {
dateStr := "05/24/2024"
dateValue, err := time.Parse("01/02/2006", dateStr) // updated layout
if err != nil {
log.Println(err.Error())
}
fmt.Println(dateValue)
dateStr = dateValue.Format("20060102")
fmt.Println(dateStr)
}
Output:
2024-05-24 00:00:00 +0000 UTC
20240524