int compareTo(Calendar anotherCalendar)
描述 (Description)
java.util.Calendar.compareTo()方法比较Calendar对象和anotherCalendar对象之间的时间值(毫秒偏移)。
声明 (Declaration)
以下是java.util.Calendar.compareTo()方法的声明
public int compareTo(Calendar anotherCalendar)
参数 (Parameters)
anotherCalendar - 要比较的Calendar对象。
返回值 (Return Value)
如果参数表示的时间等于此Calendar对象表示的时间,则该方法返回0; 或者,如果此Calendar的时间早于参数表示的时间,则值小于0; 如果此日历的时间在所代表的时间之后,则为大于0的值。
异常 (Exception)
NullPointerException - 如果指定的Calendar为null。
IllegalArgumentException - 如果无法获取指定Calendar对象的时间值
例子 (Example)
以下示例显示了java.util.calendar.compareTo()方法的用法。
package com.iowiki;
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