Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse four digit year only (with Joda Time)?

Is there a way to force Joda time to parse dates only when they contain four digit years? For example:

  • 2009-11-11 - should parse
  • 09-11-11 - should not parse

Tried the following code:

DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeFormatter formatter = builder.appendYear(4, 4).appendLiteral('-').appendMonthOfYear(1).appendLiteral('-').appendDayOfMonth(1).toFormatter();
formatter.parseDateTime("09-11-11");

Parses into 0009-11-11. Apparently minDigits in the method appendYear are only used for formatting when printing out the date.
The result is the same if I use appendYearOfEra(). If I use appendYearOfCentury(), it parses the year into 1909 instead.

We are implementing a general data parser, which will recognize various types of inputs. Also the example is a shortened form of the real deal (for simplicity). Real life scenarios parses dates which can have weekdays, months as words, time, zone and different characters separating month, day and year. Therefore, writing a RegEx or checking the content/length of the string can prove rather difficult.

Some real examples could look like this:

  • 2009-11-11
  • Wednesday 2009-11-11T15:00:00
  • 2009/11/11 15:00
  • and many more...
like image 874
Emilis Panovas Avatar asked Jan 23 '23 02:01

Emilis Panovas


2 Answers

DateTimeFormatterBuilder#appendFixedDecimal() may well do what you need.

Alternatively, you could implement the DateTimeParser interface to create whatever parser you want and pass that into the DateTimeFormatterBuilder.

like image 62
JodaStephen Avatar answered Jan 31 '23 23:01

JodaStephen


You can check the length of the date string.

like image 44
Peter Lawrey Avatar answered Jan 31 '23 23:01

Peter Lawrey