如何比较两个日期在 30 天内的情况

Sam*_*and 3 java

我试图将我的表单设置为指定两个日期在 30 天内的逻辑。

Date fromDate = form.getFromDate();
Date toDate = form.getToDate();
if(fromDate.compareTo(toDate) > 30){ // if the selected date are within one month

 } 
Run Code Online (Sandbox Code Playgroud)

我想添加类似的验证以确保所选的两个日期在月份范围内

Xir*_*ema 5

如果您有 Java 8 或更高版本,那么以下代码是理想的选择:

Instant fromInstant = fromDate.toInstant();
Instant toInstant = toDate.toInstant();
Duration duration = Duration.between(fromInstant, toInstant);
final Duration THIRTY_DAYS = Duration.ofDays(30);

if(duration.compareTo(THIRTY_DAYS) < 0) {
    //Duration is less than thirty days
} else if(duration.compareTo(THIRTY_DAYS) > 0) {
    //Duration is more than thirty days
} else {
    //Duration is exactly thirty days.... somehow....
}
Run Code Online (Sandbox Code Playgroud)

如果您需要一个“概念”月份(持续时间可能在 28-31 天之间变化),而不是确切的 30 天,那么以下代码更好:

//Replace with the exact time zone of these dates
//if it's not the same as the time zone of the computer running this code.
ZoneId zoneId = ZoneId.systemDefault(); 

LocalDate fromLocalDate = LocalDate.ofInstant(fromDate.toInstant(), zoneId);
LocalDate toLocalDate = LocalDate.ofInstant(toDate.toInstant(), zoneId);
Period period = Period.between(fromLocalDate, toLocalDate);
final Period ONE_MONTH = Period.ofMonths(1);

if(period.compareTo(ONE_MONTH) < 0) {
    //Difference is less than one month
} else if(period.compareTo(ONE_MONTH) > 0) {
    //Difference is greater than one month
} else {
    //Difference is exactly one month
}
Run Code Online (Sandbox Code Playgroud)