我需要检查给定日期是否在当前月份,我编写了以下代码,但 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/