日历类的compareTo()方法 (Calendar Class compareTo() method)
compareTo() method is available in java.util package.
compareTo()方法在java.util包中可用。
compareTo() method is used to compare two Calendar objects or in other words, we can say this method is used to compare the time of this Calendar object and the given Calendar object.
compareTo()方法用于比较两个Calendar对象,换句话说,可以说该方法用于比较此Calendar对象和给定Calendar对象的时间。
compareTo() method is a non-static method, it is accessible with the class object and if we try to access the method with the class name then we will get an error.
compareTo()方法是一种非静态方法,可通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
compareTo() method may throw an exception at the time of comparing two Calendar objects.
比较两个Calendar对象时, compareTo()方法可能会引发异常。
- NullPointerException: This exception may throw when the given parameter is null exists.NullPointerException :当给定参数为null时,可能引发此异常。
- IllegalArgumentException: This exception may throw when the time of the given Calendar object is illegal.IllegalArgumentException :如果给定Calendar对象的时间非法,则可能引发此异常。
Syntax:
句法:
public int compareTo(Calendar obj2);
Parameter(s):
参数:
Calendar obj – represents the Calendar object to be compared with this Calendar object.
Calendar obj –表示要与此日历对象进行比较的Calendar对象。
Return value:
返回值:
The return type of this method is int, it returns the following values based on the below given cases,
此方法的返回类型为int ,它基于以下给定情况返回以下值:
It returns 0 if this Calendar time value is the same as the given Calendar time.
如果此日历时间值与给定的日历时间相同,则返回0 。
It returns the value < 0 if the time denoted by this Calendar is before the time denoted by the given Calendar parameter.
如果此Calendar表示的时间早于给定Calendar参数表示的时间,它将返回值<0 。
It returns the value > 0 if this Calendar time is after the time denoted by the given Calendar parameter.
如果此日历时间晚于给定Calendar参数指示的时间,它将返回值> 0 。
Example:
例:
// Java Program to demonstrate the example of
// int compareTo(Object) method of Calendar
import java.util.*;
public class CompareOfCalendar {
public static void main(String[] args) {
// Instantiating two Calendar object
Calendar ca1 = Calendar.getInstance();
Calendar ca2 = Calendar.getInstance();
// By using add() method to add the 10 years
// in ca2 to the current ca1
ca2.add(Calendar.YEAR, 10);
// Display ca1 and ca2
System.out.println("ca1: " + ca1.getTime());
System.out.println("ca2: " + ca2.getTime());
// By using compareTo(Object) method is to
// compare two calendar ca1 and ca2
int comp = ca1.compareTo(ca2);
// Display compared result
System.out.println("ca1.compareTo(ca2): " + comp);
}
}
Output
输出量
ca1: Thu Jan 23 11:51:26 GMT 2020
ca2: Wed Jan 23 11:51:26 GMT 2030
ca1.compareTo(ca2): -1
翻译自: https://www.includehelp.com/java/calendar-compareto-method-with-example.aspx