Is there a good date parser for Java?

2019-01-17 03:59发布

Does anyone know a good date parser for different languages/locales. The built-in parser of Java (SimpleDateFormat) is very strict. It should complete missing parts with the current date.

For example

  • if I do not enter the year (only day and month) then the current year should be used.
  • if the year is 08 then it should not parse 0008 because the current year pattern has 4 digits.

Edit: I want to parse the input from a user. For example if the locale date format of the user is "dd.mm.yyyy" and the user type only "12.11." then the parser should accept this as a valid date with the value "12.11.2008". The target is a good usability.

10条回答
你好瞎i
2楼-- · 2019-01-17 04:07

I would have to say +1 for JodaTime. In addition to parsing, Joda makes just about every date-related operation better.

查看更多
Rolldiameter
3楼-- · 2019-01-17 04:10

Use DateFormat ... Current standard until the welcome respite of Joda.

查看更多
做自己的国王
4楼-- · 2019-01-17 04:13

The POJava project on SourceForge has a DateTime object that parses dates from multiple languages (when month is specified as a name) and is configurable between MM-DD-YYYY and DD-MM-YYYY. It parses dates heuristically, picking out the most likely year, month, date, hour, minute, second, and time zone rather than supporting predefined formats. The jar file is about 60K in size.

There is ambiguity in interpretation of a date like "10-08" in that it could be intended as shorthand for either "2008-10-08" or "Oct 2008". You could append the year yourself if you are accepting the sort of shorthand you give in your example.

Proj: POJava Docs: HOWTO use DateTime

查看更多
姐就是有狂的资本
5楼-- · 2019-01-17 04:16

I tried to implement an extensible PHP's strtotime in Java in this answer

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-01-17 04:19

(Edited for clarity.)

Personally, I think strict is good. So many different situations call for different rules around relaxed parsing, it's impossible to really put that into a common library comprehensively.

However, I would thoroughly recommend Joda Time instead of the built-in date/time classes in general. Their formatters and parsers are thread-safe and immutable, which helps too. Joda Time has some support for relaxed parsing, as shown in the other answer, but you should expect to have to provide some of the rules yourself.

查看更多
冷血范
7楼-- · 2019-01-17 04:20

I would say JChronic if you're looking for something that will parse dates from natural "fuzzy" human input.

I've used both JChronic and Chronic (the original Ruby version) with great success.

查看更多
登录 后发表回答