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);
I agree with Pallavi Sonal’s answer that when you can use the modern java.time
classes, you should keep your use of the oldfashioned classes like Date
to an absolute minimum. I don’t know JXDatePicker, but I see that its getDate method returns a Date
. So the first thing you should do with this is convert it to a more modern thing.
It may seem from your question that in this case you are only concerned with days, not times. If this is correct, Pallavi Sonal is also correct that LocalDate
is the correct class for you. I think that this conversion should work for you
LocalDate selectedDate = jXDatePicker.getDate()
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
This is with a bit of reservation for time zone issues since I don’t know in which time zone the date picker is giving you the date. Once you know that, you can fill in the correct time zone instead of ZoneId.systemDefault()
.
Unfortunately I am not aware of a date picker component that can give you a LocalDate
directly. There could well be one, I hope there is, so it’s probably worth searching for one.