How to calculate the difference between current day and date of the object that user had previously selected from jXDatePicker
swing component and that had been add
You are mixing up the legacy Date-Time code with the new Java 8 Date-Time API. The ChronoUnit.between(Temporal, Temporal)
method is from java.time.temporal
package which takes two Temporal objects. It does not support the java.util.Date
as an argument, hence the compilation error.
Instead of using the legacy Date
class, you can use java.time.LocalDate
class , and then get the difference between the two dates.
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
LocalDate objDate = obj.getSelectedDate(); // object should also store date as LocalDate
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);
As per your comment , the objDate can only be a Date, so in this case you can use the inter-operability between the Legacy Date -Time and the Java 8 Date-Time classes.
LocalDateTime currentDate = LocalDateTime.now(ZoneId.systemDefault());
Instant objIns = obj.getSelectedDate().toInstant();
LocalDateTime objDtTm = LocalDateTime.ofInstant(objIns, ZoneId.systemDefault());
long daysDifference = ChronoUnit.DAYS.between(objDtTm, currentDate);
Update 2
As pointed out by Ole V.V in the comments, to handle Time Zone issues that may occur , calculating the difference using Instant
is a better approach.
Instant now = Instant.now();
long daysDifference = obj.getSelectedDate()
.toInstant()
.until(now, ChronoUnit.DAYS);