Checks if two calendar objects represent the same local time in Java

Java 8Object Oriented ProgrammingProgramming

Use the == operator to compare two calendar objects.

Let us first create the first calendar object and set date −

Calendar date1 = Calendar.getInstance();
date1.set(Calendar.YEAR, 2040);
date1.set(Calendar.MONTH, 10);
date1.set(Calendar.DATE, 25);
date1.set(Calendar.HOUR_OF_DAY, 11);
date1.set(Calendar.MINUTE, 30);
date1.set(Calendar.SECOND, 10);

Now, the following is the second calendar object −

Calendar date2 = Calendar.getInstance();
date2.set(Calendar.YEAR, 2040);
date2.set(Calendar.MONTH, 10);
date2.set(Calendar.DATE, 25);
date2.set(Calendar.HOUR_OF_DAY, 11);
date2.set(Calendar.MINUTE, 30);
date2.set(Calendar.SECOND, 10);

Let is now compare them using == and && operators −

if(date1.get(Calendar.SECOND) == date2.get(Calendar.SECOND) &&
date1.get(Calendar.MINUTE) == date2.get(Calendar.MINUTE) &&
date1.get(Calendar.HOUR) == date2.get(Calendar.HOUR) &&
date1.get(Calendar.DAY_OF_YEAR) == date2.get(Calendar.DAY_OF_YEAR) &&
date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) ) {
   System.out.println("The local time for the calendar objects is same...");
   } else {
  System.out.println("The local time for the calendar objects are different...");
}

The following is the final example −

Example

 Live Demo

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Calendar date1 = Calendar.getInstance();
      date1.set(Calendar.YEAR, 2040);
      date1.set(Calendar.MONTH, 10);
      date1.set(Calendar.DATE, 25);
      date1.set(Calendar.HOUR_OF_DAY, 11);
      date1.set(Calendar.MINUTE, 30);
      date1.set(Calendar.SECOND, 10);
      java.util.Date dt1 = date1.getTime();
      System.out.println("Date One = "+dt1);
      Calendar date2 = Calendar.getInstance();
      date2.set(Calendar.YEAR, 2040);
      date2.set(Calendar.MONTH, 10);
      date2.set(Calendar.DATE, 25);
      date2.set(Calendar.HOUR_OF_DAY, 11);
      date2.set(Calendar.MINUTE, 30);
      date2.set(Calendar.SECOND, 10);
      java.util.Date dt2 = date2.getTime();
      System.out.println("Date two = "+dt2);
      if(date1.get(Calendar.SECOND) == date2.get(Calendar.SECOND) &&
      date1.get(Calendar.MINUTE) == date2.get(Calendar.MINUTE) &&
      date1.get(Calendar.HOUR) == date2.get(Calendar.HOUR) &&
      date1.get(Calendar.DAY_OF_YEAR) == date2.get(Calendar.DAY_OF_YEAR) &&
      date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) ) {
      System.out.println("The local time for the calendar objects is same...");
      } else {
         System.out.println("The local time for the calendar objects are different...");
      }
   }
}

Output

Date One = Sun Nov 25 11:30:10 UTC 2040
Date two = Sun Nov 25 11:30:10 UTC 2040
The local time for the calendar objects is same...
raja
Published on 19-Dec-2018 13:29:13
Advertisements