Java LocalDate doesn't accept all EpochDay field valid values

Viewed 1630
LocalDate.ofEpochDay(ChronoField.EPOCH_DAY.range().getMinimum());

This code above finish with the following stack trace thrown:

java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999): -1000018564
  at java.time.temporal.ValueRange.checkValidIntValue(ValueRange.java:330)
  at java.time.temporal.ChronoField.checkValidIntValue(ChronoField.java:722)
  at java.time.LocalDate.ofEpochDay(LocalDate.java:341)

I did not understand why this instruction is unsupported.

Actually, java-time strategy is query the own Temporal its ValueRange for anTemporalField through range (TemporalField) method. And, for this case LocalDate does not change the EpochDay field default range.

@Override
public ValueRange range(TemporalField field) {
    if (field instanceof ChronoField) {
        ChronoField f = (ChronoField) field;
        if (f.isDateBased()) {
            switch (f) {
                case DAY_OF_MONTH: return ValueRange.of(1, lengthOfMonth());
                case DAY_OF_YEAR: return ValueRange.of(1, lengthOfYear());
                case ALIGNED_WEEK_OF_MONTH: return ValueRange.of(1, getMonth() == Month.FEBRUARY && isLeapYear() == false ? 4 : 5);
                case YEAR_OF_ERA:
                    return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE));
            }
            return field.range();
        }
        throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
    }
    return field.rangeRefinedBy(this);
}

EpochDay field valid values should be transformable to LocalDate, otherwise why long is it in the range?

The same occurs with Instant and INSTANT_SECONDS field: Instant.ofEpochSecond(ChronoField.INSTANT_SECONDS.rangeRefinedBy(Instant.now()).getMinimum());

Can someone help me, please?

1 Answers

Seems to be a bug in Java 8 Update 181 at least, fixed by Java 10 at least.

Java 10 - Pass

Works for me, Java 10.0.2, Zulu JVM by Azul Systems, on macOS High Sierra.

LocalDate ld = 
    LocalDate.ofEpochDay( 
        ChronoField.EPOCH_DAY.range().getMinimum() 
    )
;
System.out.println( ld );

-999999999-01-01

Java 8 - Fail

Throws exception on Java 1.8.0_181, Zulu JVM by Azul Systems, on macOS High Sierra.

Exception in thread "main" java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999): -1000018564 at java.time.temporal.ValueRange.checkValidIntValue(ValueRange.java:330) at java.time.temporal.ChronoField.checkValidIntValue(ChronoField.java:722) at java.time.LocalDate.ofEpochDay(LocalDate.java:341)

The offending line seems to be # 341 in the LocalDate.java file.

int year = YEAR.checkValidIntValue(yearEst);

…where yearEst is -1000018564

Related