java.util.Calendar compareTo(Calendar anotherCalendar)

Description :

This java tutorial shows how to use the compareTo(Calendar anotherCalendar) method of Calendar class of java.util package. This method compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.

Method Syntax :

public int compareTo(Calendar anotherCalendar)

Parameter Input :

 

DataType Parameter Description
Calendar anotherCalendar the Calendar to be compared

 

Method Returns :

This method 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.

Compatibility Version :

Requires Java 1.5 and up

Exception :

N/A

Java Code Example :

This java example source code demonstrates the use of compareTo(Calendar anotherCalendar)  method of Calendar class. Basically on this example we just compare two calendar object and interpret the result which one is greater.

package com.javatutorialhq.java.examples;

import java.util.Calendar;

/*
 * This example source code demonstrates the use of  
 * compareTo(Calendar anotherCalendar) method of Calendar class
 */

public class CalendarCompareToExample {

	public static void main(String[] args) {

		Calendar cal1 = Calendar.getInstance();
		System.out.println("Time 1:" + cal1.getTime());
		Calendar cal2 = Calendar.getInstance();
		cal2.setTimeInMillis(1424330998200L);
		System.out.println("Time 2:"+cal2.getTime());
		int result = cal1.compareTo(cal2);
		if(result > 0){
			System.out.println("Calendar 1 is greater than Calendar 2");
			
		}
		else if(result < 0){
			System.out.println("Calendar 1 is less than Calendar 2");			
		}
		else{
			System.out.println("Calendar 1 is equal to Calendar 2");
		}
	}
}

Sample Output :

Running the compareTo(Calendar anotherCalendar) method example source code of Calendar class will give you the following output:

Time 1:Sun Feb 08 01:45:40 CST 2015
Time 2:Thu Feb 19 15:29:58 CST 2015
Calendar 1 is less than Calendar 2

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :