views:

215

answers:

2

Is there a simple way to parse a date that may be in MM/DD/yyyy, or M/D/yyyy, or some combination? i.e. the zero is optional before a single digit day or month.

To do it manually, one could use:

String[] dateFields = dateString.split("/");
int month = Integer.parseInt(dateFields[0]);
int day = Integer.parseInt(dateFields[1]);
int year = Integer.parseInt(dateFields[2]);

And validate with:

dateString.matches("\\d\\d?/\\d\\d?/\\d\\d\\d\\d")

Is there a call to SimpleDateFormat or JodaTime that would handle this?

+7  A: 

Yep, use setLenient:

DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
df.setLenient(true);
System.out.println(df.parse("05/05/1999"));
System.out.println(df.parse("5/5/1999"));
toolkit
Actually, for Ray's question, the date format should be: DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Tebari
The parsing still works, even when setting lenient to false.
Herman Lintvelt
Swapped dd and MM round. Thanks Tebari
toolkit
A: 

Looks like my problem was using "MM/DD/yyyy" when I should have used "MM/dd/yyyy". Uppercase D is "Day in year", while lowercase d is "Day in month".

new SimpleDateFormat("MM/dd/yyyy").parse(dateString);

Does the job. Also, "M/d/y" works interchangeably. A closer reading of the SimpleDateFormat API Docs reveals the following:

"For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields."

Ray Myers