0

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));

   }
}
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
  • @Jens: I tried compareTo and equal. However, I realised that equal is using a time stamp. That's why I'm asking how to ignore it. – Klausos Klausos Aug 31 '15 at 11:59
  • Why do you compare calendars? –  Aug 31 '15 at 12:00
  • You have to write your own compare method. – Jens Aug 31 '15 at 12:01
  • If you don't want to create your own method, you could simply set hour, minute and second to 0, then compare. Or just use `Date`, which [makes it easier](http://stackoverflow.com/questions/1439779/how-to-compare-two-dates-without-the-time-portion) – BackSlash Aug 31 '15 at 12:02

3 Answers3

4

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)
kostya
  • 9,221
  • 1
  • 29
  • 36
1

Since you are comparing the two instances using equals, they can only be equal if they represent exactly the same timestamp. See the java.util.GregorianCalendar#equals Javadoc:

Compares this GregorianCalendar to the specified Object. The result is true if and only if the argument is a GregorianCalendar object that represents the same time value (millisecond offset from the Epoch) under the same Calendar parameters and Gregorian change date as this object.

So after you change the value of cal2 to something different, it can never be equal to cal1.

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
0

If you want to compare dates use the following code:

// compare the two dates
System.out.println("Date1 and date2 are equal:" + cal1.getTime().equals(cal2.getTime()));