java - 如何比较两个日期在 30 天内

标签 java

当两个日期都在 30 天内时,我正在尝试将表单设置为特定逻辑。

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

 } 

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

最佳答案

如果您有 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....
}

如果您需要一个“概念”月份(其持续时间可以从 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
}

关于java - 如何比较两个日期在 30 天内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48233470/

相关文章:

Java:Spring 框架:声明嵌套映射

java - 正确实现分数的 equals() 方法

java - 如何制作帖子正文请求中所需的输入属性?

java - 需要在Java中使用eclipse获取MongoDB中的一个字段

java - BIGINT UNSIGNED 自动增量被 mybatis 破坏

java - 是否可以声明并实现一个方法一次,但改变返回类型以稳健地匹配子接口(interface)?

java - 从字符串中删除多个子字符串 - Java

java - 在收到对等方的 close_notify 之前关闭入站

java - 如何创建Java类ScheduledThreadPoolExecutor的bean

java - 使用 SWIG 的 C 函数的 JNI 包装器 - 类型映射应该是什么?