“no suitable method found for between(Date, Date)" when trying to calculate difference in days between two dates

前端 未结 2 1493
一个人的身影
一个人的身影 2021-01-29 13:31

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

2条回答
  •  遇见更好的自我
    2021-01-29 13:44

    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);
    

    Update

    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);
    

提交回复
热议问题