The difference between 2 Instants in Calendar Days

TOTOROCATBUS picture TOTOROCATBUS · Jul 17, 2018 · Viewed 8.2k times · Source

So I'm trying to get a specific number with my code. Right now I have:

Instant Today = 2018-07-17T13:45:00Z
Instant Expiration1 = 2018-07-18T11:00:00Z
long daysTilExp = Today.until(Expiration, Chronounit.DAYS)

The problem is that because this isn't exactly 24 hours apart it ends up returning daysTilExp = 0 but I want daysTilExp = 1 I'm trying to get that actual days apart the two Instants are so then even If I change the value of Expiration like so:

Instant Expiration1 = 2018-07-18T06:00:00Z

and now daysTilExp = 2. I looked at some other answers on StackOverflow but it doesn't look like people are using Instant and they aren't wanting the difference the same way

Answer

Pavel Molchanov picture Pavel Molchanov · Jul 17, 2018

LocalDate will remove the time part and LocalDate objects comparison will yield the expected result:

LocalDateTime  today = LocalDateTime.parse("2018-07-17T13:45:00");
LocalDateTime  expiration = LocalDateTime.parse("2018-07-18T11:00:00");
LocalDate todayDate = today.toLocalDate();
LocalDate expirationDate = expiration.toLocalDate();
long days = todayDate.until(expirationDate, ChronoUnit.DAYS);
System.out.println(days);