Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing Ambiguous Dates in Java

Tags:

java

Is there any way in Java to guess the date format when it is not explicitly defined?

For example a user types in 11Mar09 or 11-09-2009 or 11/09/2009 or 11-09 what is the best way of parsing this to a Date object without either a bunch of try catch or raising an error?

like image 622
Tobias M Avatar asked May 02 '26 03:05

Tobias M


2 Answers

I don't think you want to do this, especially based on your examples, but if you must, I think your best bet will be to use something like Apache's DateUtils in commons-lang:

String[] datePatterns = new String[] {
  "ddMMMyy",    // ex. 11Mar09
  "dd-MM-yyyy", // ex. 11-09-2009
  "dd/MM/yyyy", // ex. 11/09/2009
  "dd-MM"       // ex. 11-09 
}

Date date = DateUtils.parseDate(stringDate, datePatterns);

Unfortunately dates like the fourth one above will be problematic - is "11/09" September 11th, November 9th, September 2011, November 2009, or something else?

like image 168
SingleShot Avatar answered May 03 '26 17:05

SingleShot


My recommendation is don't. Use a date picker or an explicitely noted format. Guessing will lead to all kinds of problems, easily including, if the date is a critical one, litigation.

If you have to guess, provide some form of feedback that is non-ambiguous, something like a confirmation page that says "Your flight will be booked on the 9th of November, 2009. Is this correct?".

like image 29
Michael Rutherfurd Avatar answered May 03 '26 18:05

Michael Rutherfurd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!