Originally posted by Jeff Albertson: I hope you realize that asking if the string is a valid date is very different from asking whether it consists of only numbers!!!
For the date question, definitely use a SimpleDateFormat -- rolling your own would be silly. (Leap years, the start of the Gregorian calendar...)
Out of curiousity, how hard is it to parse all of these date formats using SimpleDateFormat?
MMDDYYYY MM.DD.YYYY M.DD.YYYY MM.D.YYYY
MMDDYY MM.DD.YY M.DD.YY MM.D.YY
YYYYMMDD YYYY.MM.DD YYYY.M.DD YYYY.MM.D
YYMMDD YY.MM.DD YY.M.DD YY.MM.D
Where . is any separator \/.-? I ask because we do it in about 100 lines, but it seems overly complex. I just don't see any easy way to accomplish that without a horribly absurd number of SimpleDateFormats.
Ken, are you trying to parse them all simultaneously? Accept one string as input and decide which of the available formats it fits? What about something like "060708"? Is that MMDDYY or YYMMDD? Or am I misunderstanding your goal here?
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
...more information in parse(String, ParsePosition)
By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).
It's not parsing the f, it's looking at it as if it were 2006031 and assuming it's in YYYYMMD format. If you want to force it to look at the entire thing then do setLenient(false) prior to formatting it. [ May 19, 2006: Message edited by: Ken Blair ]
Surprisingly, setLenient(false) isn't good enough here. This API was written long ago by somone who preferred to hide errors rather than make them obvious; I have little patience for such code. However, this works:
You're right. I misunderstood that part of the documentation, it only throws an exception if it errors out on the very first character. That seems horribly illogical. Why would I want an exception when it fails on the first character but not if it fails on any other?