-2

I am trying to calculate the number of days between two dates. Even though I found many similar questions, I just cannot come up with a solution.

Date lastpickup = (Date) section_userdata.get("lastpickup");
Date today = new Date();
    
Instant instant_lastpickup = lastpickup.toInstant().truncatedTo(ChronoUnit.DAYS);
Instant instant_today = today.toInstant().truncatedTo(ChronoUnit.DAYS);

This is my code at the moment. A date is read from a config and should be compared to the actual date. With the code I have I am able to determine whether the date is the same or not, but I want to know which amount of days (ideally as an Integer) is between those two.

I want to look at the calendar days, not 24h rhythm.

prmln
  • 19
  • 1
  • 1
    Well, the result will depend on the timezone. Which timezone do you want to do the operation in? – Sweeper Mar 02 '21 at 11:49
  • FYI, never use `java.util.Date` nor `java.sql.Date`. Both are legacy classes, supplanted years ago by the modern *java.time* classes defined in JSR 310. Specifically replaced by `java.time.Instant` and `java.time.LocalDate`, respectively. – Basil Bourque Mar 02 '21 at 21:55

1 Answers1

2

Well, it was way easier than I thought.

Here's my solution

long daysCount = ChronoUnit.DAYS.between(instant_lastpickup, instant_today);
prmln
  • 19
  • 1