javajsr310

JSR310 Year.parse() throws DateTimeParseException with values < 1000


I'm trying to parse Year String values in the range from 0 to 1000 with java.time.Year.parse(), however parsing fails with java.time.format.DateTimeParseException: Text '999' could not be parsed at index 0.

The javadoc of Year.parse states:

Obtains an instance of Year from a text string such as 2007. 
The string must represent a valid year. Years outside the range 0000 to 9999 
must be prefixed by the plus or minus symbol.

Example test to reproduce this issue:

@Test
public void parse_year() {
   for (int i = 2000; i >= 0; i--) {
      System.out.println("Parsing year: " + i);
      Year.parse(String.valueOf(i));
   }
}

The test throws the exception when year 999 is reached:

Parsing year: 1003
Parsing year: 1002
Parsing year: 1001
Parsing year: 1000
Parsing year: 999
java.time.format.DateTimeParseException: Text '999' could not be parsed at index 0
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.Year.parse(Year.java:292)
    at java.time.Year.parse(Year.java:277)
[...]

What am I doing wrong?


Solution

  • needs to be padded to 4 digits

    Year.parse(String.format("%04d", i));
    
    Parsing year: 2000
    Parsing year: ....
    Parsing year: 4
    Parsing year: 3
    Parsing year: 2
    Parsing year: 1
    Parsing year: 0
    

    If you wanted to parse before year 0, you could use

    Year.parse("-0001");