How to make out only a four-digit year (with Joda Time)?

Is there a way to get Joda's time to analyze dates only when they contain four digits of years? For instance:

  • 2009-11-11 - must understand
  • 09-11-11 - do not understand

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 in 0009-11-11. Apparently, minDigits in the appendYear method are used only for formatting when printing a date.
The result is the same if I use appendYearOfEra (). If I use appendYearOfCentury (), it analyzes the year in 1909.

We implement a common data analyzer that will recognize various types of inputs. Another example is a shortened form of a real transaction (for simplicity). Real-life scenarios analyze dates that may have days of the week, months as words, time, zone, and various characters separating the month, day, and year. Therefore, writing RegEx or checking the contents / line length can be quite complicated.

Some real examples might look like this:

  • 2009-11-11
  • Wednesday 2009-11-11T15: 00: 00
  • 2009/11/11 15:00
  • and much more...
+4
source share
4 answers

DateTimeFormatterBuilder.appendFixedDecimal () can do what you need.

Alternatively, you can implement the DateTimeParser interface to create any parser you want and pass it to a DateTimeFormatterBuilder.

+6
source

You can create extremely specific parsers and formatting elements using DateTimeFormatterBuilder . As a rule, there is no need to use this class directly, since most common formats are more easily accessible elsewhere in the API, but it is a class of builders, which they all use under the covers.

+1
source

You can check the length of the date string.

+1
source

What do you want to get from a user who enters “0001-01-01” as a date (that is, they entered 4 digits for the year, but the first three were zeros)? What about '0999-12-31'? And '999-12-31'? What about "10000-01-01" - the notorious issue of Y10K 1 ?

  • If this is a legitimate value, you are stuck in detecting the length of what the user entered as the annual part of the date (perhaps after any other analysis), and make sure that it is on (or is it for sure?) Four digits.

  • If this is not a legitimate value, you are stuck in checking the year value after the date has been analyzed.

  • Or, you can take the code and change it to include your preferred definition of a valid year.


1 I do not plan to begin work on fixing the Y10K problem before 5000-01-02.

0
source

All Articles