Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

What is the difference between instant and LocalDateTime?

Instant – represents a point in time (timestamp) LocalDate – represents a date (year, month, day) LocalDateTime – same as LocalDate, but includes time with nanosecond precision.

What is the difference between ZonedDateTime and LocalDateTime?

A LocalDateTime instance represents a point in the local timeline. It cannot represent an instant on the universal timeline without additional information such as an offset or time zone. A ZonedDateTime instance represents an instant in the universal timeline. It is the combination of date, time and zone information.

Is Instant always UTC?

For example, 2022-06-29T12:01:25.369081700Z. Note:- Instant date/time are time-zone unaware and it always returns current date/time at UTC/GMT.


I want to use MIN/MAX time values that can convert between ZonedDateTime and Instant.toEpochMilli(), to be used as sentinel values for a 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 that returns the same exception as the last one.

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 that the best solution?