當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#compareTo(java.util.Calendar)



相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Calendar compareTo() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。