Parsing Ambiguous Dates in Java

后端 未结 4 1012
谎友^
谎友^ 2020-12-19 23:31

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

4条回答
  •  旧时难觅i
    2020-12-20 00:22

    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?

提交回复
热议问题