Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between 2 Instants in Calendar Days

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

like image 394
TOTOROCATBUS Avatar asked Nov 15 '25 19:11

TOTOROCATBUS


2 Answers

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);
like image 126
Pavel Molchanov Avatar answered Nov 18 '25 09:11

Pavel Molchanov


The best way is using DAYS.between() method from java.time.temporal.ChronoUnit. But this way works only for Java 8+ versions. Example:

Date start = new Date();
Date end = new Date(start.getTime() + 10_000);
long daysCount = DAYS.between(start.toInstant(), end.toInstant());
like image 36
gnupinguin Avatar answered Nov 18 '25 09:11

gnupinguin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!