📜  Java中的 Calendar compareTo() 方法及示例

📅  最后修改于: 2022-05-13 01:55:20.604000             🧑  作者: Mango

Java中的 Calendar compareTo() 方法及示例

Calendar 类的add(Calendar Calendar2 )方法用于将此 Calendar 对象的时间值或毫秒偏移量与传递的 Calendar 对象进行比较。

句法:

public int compareTo(Calendar Calendar2)

参数:该方法采用Calendar对象类型的一个参数Calendar2,并引用要与此Calendar对象进行比较的对象。

返回值:该方法返回一个整数值,可以返回以下任意一种:

  1. 如果传递的参数等于此 Calendar 对象,则该方法返回 0。
  2. 如果此 Calendar 对象的时间大于传递的对象,则该方法返回 1。
  3. 如果此 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

参考: https: Java Java.util.Calendar)