Calendar类的add(Calendar Calendar2)方法用于将此Calendar对象的时间值或毫秒偏移与传递的Calendar对象进行比较。
用法:
public int compareTo(Calendar Calendar2)
参数:该方法采用Calendar对象类型的一个参数Calendar2,表示要与该Calendar对象进行比较的对象。
返回值:该方法返回一个整数值,并且可以返回以下任意一项:
如果传递的参数等于此Calendar对象,则该方法返回0。
如果此Calendar对象的时间大于传递的对象,则该方法返回1。
如果此Calendar对象的时间小于传递的对象,则该方法返回-1。
以下示例程序旨在说明Calendar类的compareTo()方法的用法:
示例1:
// Java Code to illustrate compareTo() Method
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr1
= Calendar.getInstance();
// Creating another calendar object
Calendar calndr2
= new GregorianCalendar(2018, 12, 2);
// Comparing the time
int val = calndr1.compareTo(calndr2);
// Displaying the result of comparison
System.out.println("First"
+ " comparison result is: "
+ val);
// Comparing the time
val = calndr2.compareTo(calndr1);
// Displaying the result of comparison
System.out.println("Second"
+ " comparison result is: "
+ val);
}
}
输出:
First comparison result is: 1
Second comparison result is: -1
示例2:
// Java Code to illustrate compareTo() Method
import java.util.*;
public class CalendarClassDemo {
public static void main(String args[])
{
// Creating a calendar object
Calendar calndr1 = Calendar.getInstance();
// Creating another calendar object
Calendar calndr2 = Calendar.getInstance();
// Comparing the time
int val = calndr1.compareTo(calndr2);
// Displaying the result of comparison
System.out.println("The"
+ " comparison result is: "
+ val);
}
}
输出:
The comparison result is: -1