Calendar compareTo() Method in Java with Examples
Last Updated :
13 Feb, 2019
The add(Calendar Calendar2) method of Calendar class is used to compare the time values or the millisecond offsets of this Calendar object with the passed Calendar object.
Syntax:
public int compareTo(Calendar Calendar2)
Parameters: The method takes one parameter Calendar2 of Calendar object type and refers to the object to be compared to this Calendar object.
Return Value: The method returns an integer value and can return any one of the following:
- The method returns 0 if the passed argument is equal to this Calendar object.
- The method returns 1 if the time of this Calendar object is more than the passed object.
- The method returns -1 if the time of this Calendar object is less than the passed object.
Below programs illustrate the working of compareTo() Method of Calendar class:
Example 1:
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
Calendar calndr1
= Calendar.getInstance();
Calendar calndr2
= new GregorianCalendar( 2018 , 12 , 2 );
int val = calndr1.compareTo(calndr2);
System.out.println( "First"
+ " comparison result is: "
+ val);
val = calndr2.compareTo(calndr1);
System.out.println( "Second"
+ " comparison result is: "
+ val);
}
}
|
Output:
First comparison result is: 1
Second comparison result is: -1
Example 2:
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
Calendar calndr1 = Calendar.getInstance();
Calendar calndr2 = Calendar.getInstance();
int val = calndr1.compareTo(calndr2);
System.out.println( "The"
+ " comparison result is: "
+ val);
}
}
|
Output:
The comparison result is: -1
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#compareTo(java.util.Calendar)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...