Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: check if a given date is within current month

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();
}
like image 519
TonyGW Avatar asked Nov 09 '14 01:11

TonyGW


People also ask

How do you check if a date is within a date range in Java?

We can use the simple isBefore , isAfter and isEqual to check if a date is within a certain date range; for example, the below program check if a LocalDate is within the January of 2020. startDate : 2020-01-01 endDate : 2020-01-31 testDate : 2020-01-01 testDate is within the date range.

How do you check if a date is after another date in Java?

To compare dates if a date is after another date, use the Calendar. after() method.

What is now () in Java?

The now() method of the LocalTime class in Java is used to get the current time from the system clock in the default time-zone.


1 Answers

//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
    }
}
like image 56
Yusuf Kapasi Avatar answered Sep 29 '22 16:09

Yusuf Kapasi