Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date time parsing that accepts 05/05/1999 and 5/5/1999, etc

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?

like image 934
Ray Myers Avatar asked Dec 09 '22 22:12

Ray Myers


1 Answers

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"));
like image 156
toolkit Avatar answered Jan 31 '23 18:01

toolkit