java - compare two date values for the month and year

Viewed 17229

I have a requirement to match two dates and if their month/year are same, i should return true, otherwise false. Based on my search, i found the following solution. Is there any other better way to do this comparison?.

Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);
    boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                      cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
3 Answers

Fast way: With JodaTime libary.

  • First, make sure that you downloaded/implemented it.
  • Then import.
import org.joda.time.LocalDate;
import java.util.Date;
  • Here you go:
Date Date1 = new Date();
Date Date2 = new Date();

if (new LocalDate(Date1).getYear() == new LocalDate(Date2).getYear()) {
 // Year Matches
 if (new LocalDate(Date1).getMonthOfYear() == new LocalDate(Date2).getMonthOfYear()) {
  // Year and Month Matches
 }
}
Related