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?
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 . ?".
, , , , , - - Apache DateUtils commons-lang:
DateUtils
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 - ?
, . , DateFormats , , .
, , , , , . , , "" "" - /.
, , . .
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.