1

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"

ahin
  • 23
  • 4
  • Here is an example on how you could do that: https://github.com/spf13/cast/blob/master/caste.go#L1206. Even better, you can use this library to get this functionality out-of-the-box. – Tarun Khandelwal Jun 30 '20 at 15:47
  • Inside the loop if `err` is `nil`, then return, don't proceed to the next format. Only try more (next) format if there's an error. After the loop, if none of the formats worked, then return an error. – icza Jun 30 '20 at 15:49
  • 2
    `"01/2/2006"` parses both of these strings without error. Even a leading zero is not a problem. – Peter Jun 30 '20 at 15:52
  • Thanks guys for the suggestions. I found @Peter 's solution, out of these comments, to be easiest. Didn't know that we could use '2' to represent single+double digits of month. – ahin Jul 01 '20 at 05:48

1 Answers1

1

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)