What MIN / MAX values ​​will work with both ZonedDateTime and Instant.toEpochMilli?

I want to use temporary MIN / MAX values ​​that can convert between ZonedDateTimeand Instant.toEpochMilli(), which will be used as sentinel values ​​for the filter / query.

I tried:

OffsetDateTime.MIN.toInstant().toEpochMilli();
OffsetDateTime.MAX.toInstant().toEpochMilli();

but I get this exception:

java.lang.ArithmeticException: long overflow

    at java.lang.Math.multiplyExact(Math.java:892)
    at java.time.Instant.toEpochMilli(Instant.java:1237)

And then I tried this:

ZonedDateTime.ofInstant(Instant.MIN, ZoneId.systemDefault());
ZonedDateTime.ofInstant(Instant.MAX, ZoneId.systemDefault());

but then I get this exception:

java.time.DateTimeException: Invalid value for Year (valid values -999999999 - 999999999): -1000000001

    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)
    at java.time.LocalDateTime.ofEpochSecond(LocalDateTime.java:422)
    at java.time.ZonedDateTime.create(ZonedDateTime.java:456)
    at java.time.ZonedDateTime.ofInstant(ZonedDateTime.java:409)

I also tried "Z" ZoneId:

ZonedDateTime.ofInstant(Instant.MIN, ZoneId.of("Z"))

but returns the same exception as the last.

Finally, I tried the following and it seems to work:

ZonedDateTime.ofInstant(Instant.EPOCH, ZoneId.of("Z"));
ZonedDateTime.ofInstant(Instant.EPOCH.plusMillis(Long.MAX_VALUE), ZoneId.of("Z"));

Is this the best solution?

+6
source share
1 answer

Instant.EPOCH 1970-01-01T00:00Z, , ( , - 1970 , ).

Instant.MIN Instant.MAX ZonedDateTime , (, ).

, ZonedDateTime Instant, MIN/MAX, ( , -1000000000 1000000000), epoch milli ( ), long.

toEpochMilli(), long, long:

Instant minInstant = Instant.ofEpochMilli(Long.MIN_VALUE);
Instant maxInstant = Instant.ofEpochMilli(Long.MAX_VALUE);
ZonedDateTime minZonedDateTime = minInstant.atZone(ZoneOffset.UTC);
ZonedDateTime maxZonedDateTime = maxInstant.atZone(ZoneOffset.UTC);

:

minInstant = -292275055-05-16T16: 47: 04.192Z
maxInstant = + 292278994-08-17T07: 12: 55.807Z
minZonedDateTime = -292275055-05-16T16: 47: 04.192Z
maxZonedDateTime = + 292278994-08-17T07: 12: 55.807Z

epoch milli:

System.out.println("minInstant millis=" + minInstant.toEpochMilli());
System.out.println("maxInstant millis=" + maxInstant.toEpochMilli());

minInstant millis = -9223372036854775808
maxInstant millis = 9223372036854775807

ZoneOffset.UTC , /, . -.

Instant OffsetDateTime atOffset (, minInstant.atOffset(ZoneOffset.UTC)).


  • ZoneId.of("Z"), ZoneOffset.UTC. , ZoneId.of("Z").equals(ZoneOffset.UTC), true.
    ZoneId.of("Z") == ZoneOffset.UTC true, .
  • , . 1900 , , 2900. . , .
+6

All Articles