Parsing Ambiguous Dates in Java

后端 未结 4 997
谎友^
谎友^ 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条回答
  • 2020-12-20 00:12

    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?".

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2020-12-20 00:32

    You could have a bunch of regular expressions and cycle through until you find a match. I think you could also have a bunch of DateFormats and cycle through them, catching exceptions on ones that failed.

    The first avoids using exceptions for non-exceptional cases, the second is maybe better from a design point of view in that you're using a date parsing framework for what it was designed for. But overall, I don't think either approach is necessarily "best" or "worst" per se-- more a matter of personal preferences/beliefs.

    0 讨论(0)
  • 2020-12-20 00:32

    As the domain of possible date-strings are infinite, I don't see how it could be possible to recognize them all. You can however pick a subset for pattern-matching.

    You give no clues about your user-interface, but the best approach here would be to help the user input the date. For example with a pop-up calendar or just forcing a predefined format.

    0 讨论(0)
提交回复
热议问题