Parsing Ambiguous Dates in Java

后端 未结 4 1026
谎友^
谎友^ 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: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.

提交回复
热议问题