Java .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
0if theotherCalendaris equal to themyCalendarobject. - The method returns
1if the time of themyCalendarobject is ahead of theotherCalendarobject. - The method returns
-1if the time of themyCalendarobject is behind theotherCalendarobject.
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.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours