Parsing ambiguous dates in Java

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

For example, a user enters values ​​on 11Mar09 or 11-09-2009 or 11/09/2009 or 11-09, what is the best way to parse this Date object without any combination of attempts or raising an error?

+2
source share
4 answers

My recommendation is not . Use a date picker or an explicitly marked format. Guessing will lead to all kinds of problems, easily including, if the date is critical, a lawsuit.

, , , - , : " 9 2009 . ?".

+5

, , , , , - - Apache DateUtils 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);

, , , - "11/09" 11 , 9 , 2011 , 2009 - ?

+7

, . , DateFormats , , .

, , , , , . , , "" "" - /.

+2

, , . .

You do not give any indication of your user interface, but the best approach here is to help the user enter a date. For example, in a pop-up calendar or just a forced predetermined format.

+1
source

All Articles