.compareTo()
Anonymous contributor
Published Aug 22, 2023
Contribute to Docs
The .compareTo()
method of the Calendar
class is used to compare the time values or the millisecond offsets of two Calendar
objects.
Syntax
result = myCalendar.compareTo()
The method returns an Integer
value and can return any one of the following:
- The method returns
0
if theotherCalendar
is equal to themyCalendar
object. - The method returns
1
if the time of themyCalendar
object is ahead of theotherCalendar
object. - The method returns
-1
if the time of themyCalendar
object is behind theotherCalendar
object.
Example
This example illustrates a basic implementation of the .compareTo()
method:
import java.util.*;public class CalendarClassDemo {public static void main(String args[]){// Creating a calendar objectCalendar calndr1 = Calendar.getInstance();// Creating another calendar objectCalendar calndr2 = new GregorianCalendar(2018, 12, 2);// Comparing the timeint val = calndr1.compareTo(calndr2);// Displaying the result of comparisonSystem.out.println("First" + " comparison result is: " + val);// Comparing the timeval = calndr2.compareTo(calndr1);// Displaying the result of comparisonSystem.out.println("Second"+ " comparison result is: "+ val);}}
Output for the above code will be:
First comparison result is: 1Second comparison result is: -1
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.