“在(日期,日期)之间找不到合适的方法"尝试计算两个日期之间的天数差异时 [英] “no suitable method found for between(Date, Date)" when trying to calculate difference in days between two dates

查看:86
本文介绍了“在(日期,日期)之间找不到合适的方法"尝试计算两个日期之间的天数差异时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算用户先前从jXDatePicker摆动组件中选择的对象以及该对象作为Date添加到该对象的对象的当前日期和日期之间的差值.

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 added as Date to that object.

在当前代码的最后一行,我收到以下错误消息:

In my current code at the last line I'm getting this error message:

在(日期,日期)之间找不到合适的方法

no suitable method found for between(Date, Date)

Date currentDate = new Date();          
Date objDate = obj.getSelectedDate(); //getting date the user had 
                                      //previously selected and that been 
                                      //added to object      
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);

推荐答案

您正在将旧的Date-Time代码与新的Java 8 Date-Time API混合在一起. ChronoUnit.between(Temporal, Temporal)方法来自java.time.temporal包,该包带有两个Temporal对象.它不支持java.util.Date作为参数,因此会导致编译错误.

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.

您可以使用java.time.LocalDate类,而不是使用传统的Date类,然后获取两个日期之间的差值.

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

更新

根据您的注释,objDate只能是Date,因此在这种情况下,您可以使用Legacy Date -Time和Java 8 Date-Time类之间的互操作性.

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

更新2

Ole V.V在评论中指出,要处理可能发生的时区问题,使用Instant计算时差是一种更好的方法.

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

这篇关于“在(日期,日期)之间找不到合适的方法"尝试计算两个日期之间的天数差异时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆