Granted, I don't think the answer is critical for either performance or usability, but this question has popped into my brain.
Suppose the user is entering a date. The program doesn't know ahead of time what format it will be in, its up to the user.
2011-11-30 would be a nice format, but they are likely to entry Nov 30, 2011 or 11/30/2011 or durn near anything else.
I see two basic approaches. I'm wondering which is better, in the sense of style, good code, ease of understanding, or gross performance.
1) use a series of regex to identify which format its in, and then use that format in a SimpleDateFormat to pull out the values.
2) have a list of possible formats, and try them, in order, until you get a good value.
Pat Farrell wrote: so you don't have the "little Bobby DropTables" problem.
I see two basic approaches.
I've used both approaches and from a performance standpoint never had an issue with either.
My current preferred approach is to use the jQuery UI datepicker where I can determine what the incoming format will be and users don't have to worry about formats in the first place.
Using multiple DateFormats works (using the parse method that takes a ParsePositoon, to prevent all the ParseExceptions), but you can't recognize all formats. Even worse would be language specific input; an English user could type "Nov 30 2011" or "Nov 30, 2011", but a Dutch user would use "30 nov 2011".
Rob Spoor wrote:.Even worse would be language specific input; an English user could type "Nov 30 2011" or "Nov 30, 2011", but a Dutch user would use "30 nov 2011".
That one is actually quite easy, as alphas and digits vary. Its not just language, the US military uses the sensible 30 nov 2011 format as well.
The hard ones are locale/tradition dependent but invisible to the computer. 03/06/2011, is that Mar 6 or Jun 3? Here you have to guess based on the locale of the user.
Pat Farrell wrote:
Paul Clapham wrote: What bad things could happen if you interpret a date as 2012 June 3 instead of 2012 March 6?
The worst is that the clueless user who used a dumb format gets an answer he didn't want. GIGO.
That sounds a lot less risky than having twelve truckloads of steel I-beams show up at a construction site three months before they were needed.