Search code examples
javatimestampjava-timedatetime-comparison

Compare LocalDateTime with long


I have a timestamp (ts1) stored in a long, expressed in nanos since epoch. I want to be able to compare it with another timestamp (ts2), which I know is for today 8am

The aim is to know if ts1 is after or before ts2.

I have ts2 as below:

LocalTime eight = LocalTime.of(8, 0);
LocalDate today = LocalDate.now(ZoneId.of("Europe/Milan"));
LocalDateTime ts2 = LocalDateTime.of(today, time);

How can I compare ts2 with ts1 which is a long?


Solution

  • LocalDate and LocalDateTime are time zone agnostic. They only accept one in the now() factory to resolve the date in the specified zone, but then the time zone is discarded, so there's no way to convert it back to a particular timestamp. If you construct a ZonedDateTime instead, you can then adjust the time and extract the timestamp like this:

    long ts2 = ZonedDateTime.now(ZoneId.of("Europe/Milan"))
            .withHour(8)
            .truncatedTo(ChronoUnit.HOURS)
            .toInstant()
            .toEpochMilli();