AndreaNobili AndreaNobili - 3 months ago 14
Java Question

How to correctly check if the date (year-month-day) represented by 2 Calendar objects are the same?

into a ava application I have the following situation:

Calendar today = Calendar.getInstance();

Calendar firstDate = Calendar.getInstance();
firstDate .set(2015, 01, 16);


I have to compare if these 2 dates are the same. I am interested only to know if the year, the month and the day are the same, the other informations have not to be considered (hour, minute, second, etcetc).

What is a good way to do it?

rD. rD.
Answer

You can use The java.util.Calendar.get() method and pass values like

  • Calendar.YEAR to get year from this date
  • Calendar.MONTH to get month from this date
  • Calendar.DATE to get date from this date

For example:

if(today.get(Calendar.YEAR) == firstDate.get(Calendar.YEAR)) {
   //logic if year is same
}

if(today.get(Calendar.MONTH) == firstDate.get(Calendar.MONTH)) {
   //logic if month is same
}

if(today.get(Calendar.DATE) == firstDate.get(Calendar.DATE)) {
   //logic if date is same
}