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

前端 未结 2 1491
一个人的身影
一个人的身影 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:48

    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.

提交回复
热议问题