Java Utility Library

Java Calendar - compareTo() Method



The java.util.Calendar.compareTo() method is used to compare the time values (millisecond offsets from the Epoch) represented by two Calendar objects.

Syntax

public int compareTo(Calendar anotherCalendar)

Parameters

anotherCalendar Specify the Calendar to be compared.

Return Value

Returns the value 0 if the time represented by the argument is equal to the time represented by this Calendar; a value less than 0 if the time of this Calendar is before the time represented by the argument; and a value greater than 0 if the time of this Calendar is after the time represented by the argument.

Exception

  • Throws NullPointerException, if anotherCalendar is null.
  • Throws IllegalArgumentException, if the time value of the specified Calendar object can't be obtained due to any invalid calendar values.

Example:

In the example below, the java.util.Calendar.compareTo() method is used to compare given Calendars.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating Calendars
    Calendar Cal1 = new GregorianCalendar(98, 10, 25);
    Calendar Cal2 = new GregorianCalendar(99, 10, 25);
    Calendar Cal3 = new GregorianCalendar(97, 10, 25);

    //comparing Cal1 with Cal2
    System.out.println("Comparing Cal1 with Cal2: " + Cal1.compareTo(Cal2));

    //comparing Cal1 with Cal3
    System.out.println("Comparing Cal1 with Cal3: " + Cal1.compareTo(Cal3));

    //comparing Cal1 with Cal1
    System.out.println("Comparing Cal1 with itself: " + Cal1.compareTo(Cal1));
  }
}

The output of the above code will be:

Comparing Cal1 with Cal2: -1
Comparing Cal1 with Cal3: 1
Comparing Cal1 with itself: 0

❮ Java.util - Calendar