I have a form where users insert a date
(Edit: the input is copied form documents “as it is” so the formatting my vary)
“2012 12 01”
“2012-12-01”
“2012.12.01”
“01.15.2012”
also some not friendly (but FAST for typing!) inputs like:
“01122012” // 01 12 2012
“011212” // 01 12 2012
The input format is not fixed so I should make the bast out of what I get …
Of course there is some priority:
“12.12.12” should be parsed to yy.mm.dd IF VALID, or to dd.mm.yy as second option.
Most of the ready functions work with “properly formated” content .. so I need a alghorithm
(or good example code from parsers in other lanuages)
You could do this “straight forward” like:
In the cases where you can have two different formats you have to check the day, year and month values if they are a valid year. If so, you can build the date, otherwise try the other way.
For the yyyymmdd and mmddyyyy combinations you can use the
substr()function on the string to extract the day, year and month.However, you always have to take into account that the user input can be something incorrect like “12 March 2012” or “abcdefg”, but I would simply wrap the whole functionality into a try-catch block.