0

In a Java 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?

Aman Singh
  • 17
  • 4
AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • 3
    Get the year, get the month, get the day of each of them, and compare them? (Or ideally, move to Java 8's time API and use LocalDate instead...) – Jon Skeet Aug 24 '16 at 10:13

3 Answers3

2

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
}
Raman Sahasi
  • 30,180
  • 9
  • 58
  • 71
  • Interesting but I think that you have done an error because you always compare today, if you change it I will accept it – AndreaNobili Aug 24 '16 at 10:21
  • @AndreaNobili ya that was a minor error because I neither compiled that code, nor reviewed. Thanks for notifying, I've updated my answer accordingly. – Raman Sahasi Aug 24 '16 at 10:22
1

If you want to make it easier, i would recommend to use SimpleDateFormat in this way:

private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

private boolean areEquals(Calendar c1, Calendar c2) {
    return df.format(c1.getTime()).equals(df.format(c2.getTime()));
}

This can be used easily with your code like:

System.out.println(areEquals(today, firstDate));

Here you can find a working demo

joc
  • 1,336
  • 12
  • 31
1

java.time

You are using troublesome old legacy date-time classes now supplanted by the java.time classes.

if( myUtilCalendar instanceof GregorianCalendar ) {
    GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
    ZonedDateTime zdt = gregCal.toZonedDateTime();  // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if 

Then extract a LocalDate from each and compare.

if( thisZdt.toLocalDate().equals( thatZdt.toLocalDate() ) )…

For more discussion on conversion, and a nifty diagram, see my Answer to another Question.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154