Java.util.Calendar.compareTo() 方法
描述
java.util.Calendar.compareTo() 方法比较 Calendar 对象和 anotherCalendar 对象之间的时间值(毫秒偏移量)。
声明
以下是 java.util.Calendar.compareTo() 方法的声明
public int compareTo(Calendar anotherCalendar)
参数
anotherCalendar − 要比较的 Calendar 对象。
返回值
如果参数表示的时间等于此 Calendar 对象表示的时间,则该方法返回 0; 如果此日历的时间早于参数表示的时间,则值小于 0; 或大于 0 的值,如果此日历的时间在表示的时间之后。
异常
NullPointerException − 如果指定的日历为 null。
IllegalArgumentException − 如果无法获取指定Calendar对象的时间值
示例
下面的例子展示了 java.util.calendar.compareTo() 方法的使用。
package com.tutorialspoint;
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create two calendar at the different dates
Calendar cal1 = new GregorianCalendar(2015, 8, 15);
Calendar cal2 = new GregorianCalendar(2008, 1, 02);
// compare the time values represented by two calendar objects.
int i = cal1.compareTo(cal2);
// return positive value if equals else return negative value
System.out.println("The result is :"+i);
// compare again but with the two calendars swapped
int j = cal2.compareTo(cal1);
// return positive value if equals else return negative value
System.out.println("The result is :" + j);
}
}
让我们编译并运行上面的程序,这将产生以下结果 −
The result is :1 The result is :-1

