Java: check if a given date is within current month

TonyGW picture TonyGW · Nov 9, 2014 · Viewed 26.6k times · Source

I need to check if a given date falls in the current month, and I wrote the following code, but the IDE reminded me that the getMonth() and getYear() methods are obsolete. I was wondering how to do the same thing in newer Java 7 or Java 8.

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

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

Answer

Yusuf Kapasi picture Yusuf Kapasi · Nov 9, 2014
//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
    }
}