java.util package in Java provides the GregorianCalendar class which implements the Calendar interface and represents a calendar system used globally.
The compareTo() method in GregorianCalendar compares the time value (in milliseconds) represented by this calendar to the time value represented by the provided Calendar object. The method returns a value of 0 if the time values are equal, -1 if the time value of this calendar is before the provided calendar, and +1 if the time value of this calendar is after the provided calendar.
Example 1:
GregorianCalendar gc1= new GregorianCalendar(2021, 0, 15); GregorianCalendar gc2= new GregorianCalendar(2021, 0, 20); int result = gc1.compareTo(gc2); System.out.println("gc1 is " + (result < 0 ? "before" : result > 0 ? "after" : "the same as") + " gc2");
This code initializes two GregorianCalendar objects with different dates and compares them using the compareTo() method. The result is printed based on the comparison result.
Example 2:
GregorianCalendar gc3= new GregorianCalendar(); GregorianCalendar gc4= new GregorianCalendar(2021, 0, 20); int result = gc3.compareTo(gc4); System.out.println("gc3 is " + (result < 0 ? "before" : result > 0 ? "after" : "the same as") + " gc4");
This code initializes two GregorianCalendar objects, one with the current date and time and the other with a future date. The compareTo() method is used to compare the two calendars and print the result.
The GregorianCalendar class is part of the java.util package in Java.
Java GregorianCalendar.compareTo - 15 examples found. These are the top rated real world Java examples of java.util.GregorianCalendar.compareTo extracted from open source projects. You can rate examples to help us improve the quality of examples.