Java:检查给定日期是否在当前月份内

标签 java date java-time java.util.date

我需要检查给定日期是否在当前月份,我编写了以下代码,但 IDE 提醒我getMonth()getYear()方法已经过时。我想知道如何在较新的 Java 7 或 Java 8 中做同样的事情。

private boolean inCurrentMonth(Date givenDate) {
    Date today = new Date();

    return givenDate.getMonth() == today.getMonth() && givenDate.getYear() == today.getYear();
}

最佳答案

//Create 2 instances of Calendar
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

//set the given date in one of the instance and current date in the other
cal1.setTime(givenDate);
cal2.setTime(new Date());

//now compare the dates using methods on Calendar
if(cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)) {
    if(cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)) {
        // the date falls in current month
    }
}

关于Java:检查给定日期是否在当前月份内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824020/

相关文章:

java - 使用 AspectJ 验证初始调用递归函数的参数

java - 使用 Perl 将 Post 参数传递给 Restful Java API 时出现问题

internet-explorer - IE 输入类型日期未显示为日期选择器

r - 用日期对象拟合曲线

jsp - 在 JSP 中使用 Java8 时间

java - 在 Java 中如何检查文件中的空行然后忽略它们?

java - 在 Jar 文件中运行类

Excel:仅添加某些行中的值

java - java.time 是否无法解析秒数?

java - 如何使用DateTimeFormatter统一日期格式