ahin
ahin

Reputation: 23

How to use multiple formats to parse dates in a loop?

I am trying to read a huge csv file with a date column having value in 2 possible formats which are non-standard...

  1. 12/28/2015 -- mm/dd/yyyy
  2. 11/2/2013 -- mm/d/yyyy

...meaning the middle day component can be single or double digit.

I learnt how to use format from this nice old question: Parsing date/time strings which are not 'standard' formats. But since i am going in a loop trying to parse each row, i can specify only one format to be used at a time. Now it errors on finding date value of different format. Maybe i can code to catch error when parse-using-format#1 fails and then apply format#2, rather than erroring out. But could someone please point me to a better/correct way?

A sample code with array of date strings: https://play.golang.org/p/aloIQnrkOjK

package main

import (
    "fmt"
    "time"
)

func main() {
    const format = "01/02/2006" //mm/dd/yyyy
    var list [2]string = [2]string{"12/28/2015", "11/2/2013"}
    for _, data := range list {
        t, err := time.Parse(format, data)
        if err != nil {
            fmt.Println("Error is: ", err)
        } else {
            fmt.Println("Value is: ", t)
        }
    }
}

//Output:

Value is: 2015-12-28 00:00:00 +0000 UTC

Error is: parsing time "11/2/2013" as "01/02/2006": cannot parse "2/2013" as "02"

Upvotes: 1

Views: 2019

Answers (1)

MartinSchiznic
MartinSchiznic

Reputation: 26

The code in the question parses multiple dates with a single format. The problem is that one of the dates does not match the format (missing leading zero on day). Fix by making the leading zero optional:

const format = "1/2/2006" // remove zero before day (and month just in case)

Upvotes: 1

Related Questions