Search code examples
javagregorian-calendar

How to compare dates without time stamp using Gregorian Calendar?


How can I compare dates without time stamp using Gregorian Calendar? In the below-provided example, both results must be true.

package com.tutorialspoint;

import java.util.*;

public class GregorianCalendarDemo {

   public static void main(String[] args) {

   // create a new calendar
   GregorianCalendar cal1 = 
   (GregorianCalendar) GregorianCalendar.getInstance();

   // print the current date and time
   System.out.println("" + cal1.getTime());

   // create a second calendar equal to first one
   GregorianCalendar cal2 = (GregorianCalendar) (Calendar) cal1.clone();

   // print cal2
   System.out.println("" + cal2.getTime());

   // compare the two calendars
   System.out.println("Cal1 and Cal2 are equal:" + cal1.equals(cal2));

   // change cal 2 a bit
   cal2.add(GregorianCalendar.MINUTE, 5);

   // compare the two calendars
   System.out.println("Cal1 and Cal2 are equal:" + cal1.equals(cal2));

   }
}

Solution

  • Assuming that cal1 and cal2 have the same timezone (i.e. cal1.getTimeZone().equals(cal2.getTimeZone())) you can use the following code to compare date only:

    cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
    cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)