Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert tradional American date string to ISO date string in Go (1.2.1)?

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading