I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.
here are the formats:
9/09
9/2009
09/2009
9/1/2009
9-1-2009
What is the best way to go about trying to parse all of these? These seem to be the most common, but I guess what is hanging me up is that if i have a pattern of "M/yyyy" wont that always catch before "MM/yyyy" Do I have to set up my try/catch blocks nested in a least restrictive to most restrictive way? it seems like it sure is going to take a lot of code duplication to get this right.
Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.
}
You'll need to use a different
SimpleDateFormat
object for each different pattern. That said, you don't need that many different ones, thanks to this:So, you'll need these formats:
"M/y"
(that covers9/09
,9/2009
, and09/2009
)"M/d/y"
(that covers9/1/2009
)"M-d-y"
(that covers9-1-2009
)So, my advice would be to write a method that works something like this (untested):
In Apache commons lang, DateUtils class we have a method called parseDate. We can use this for parsing the date.
Also another library Joda-time also have the method to parse the date.