Parse date with possible single-digit month/day/hour using java.text.SimpleDateFormat

ewall picture ewall · Oct 14, 2010 · Viewed 10.2k times · Source

On a project with Talend Open Studio (an Open Source code-generating ETL tool), I am getting errors parsing incoming date strings like "3/14/1967 0:00:00" (note the single-digit month).

Digging into the code, I can see it is using java.text.SimpleDateFormat. So the date pattern string I expect I need to use is "d-M-yyyy H:mm:ss"... but it keeps giving me errors like "Unparseable date: 3/14/1967 0:00:00".

I assume that SimpleDateFormat can deal with the single-or-double digit problem. Do I need a different date pattern? (Sure, I could do pre-processing to tweak the values before Java attempts to read the strings as Dates, but it shouldn't be necessary!)

Answer

Jon Skeet picture Jon Skeet · Oct 14, 2010

Are you sure you actually need to use d-M-yyyy rather than M/d/yyyy? I can see why it would have a problem with "3/14/1967"... what date did you expect that to be? Note that not only have you got "d" and "M" the wrong way round, but you've also specified "-" instead of "/" as the separator.