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


Java Calendar.equals()用法及代碼示例


java.util.Calendar.equals()是java.util包Calendar類中的方法。該方法將此Calendar與指定的Object進行比較。如果此對象與object相等,則該方法返回true。如果不是這種情況,即兩個日曆之間的參數存在差異,則返回false。

用法:

public boolean equals(Object object)

Where, object is the Object 
to be compared with.

下麵是一些示例,以更好的方式理解Calendar.equals()函數的實現。


示例1:

Java

// Java code to show the use of 
// equals() method of Calendar class 
import java.util.*; 
  
class GFG { 
  
// Driver code 
public static void main(String[] args)  
            throws InterruptedException { 
                  
    // creating calendar object 
    Calendar cal_obj1 = Calendar.getInstance(); 
    Calendar cal_obj2 = cal_obj1; 
                  
    // printing current date 
    System.out.println("Time 1 : " + cal_obj1.getTime()); 
                  
    // printing current date 
    System.out.println("Time 2 : " + cal_obj2.getTime()); 
      
    // checking if 1st date is equal to 2nd date 
    // and printing the result 
    System.out.println(cal_obj1.equals(cal_obj2)); 
    } 
}


輸出:
Time 1 : Thu Mar 01 09:36:17 UTC 2018
Time 2 : Thu Mar 01 09:36:17 UTC 2018
true

示例2:

Java

// Java code to show the use of 
// equals() method of Calendar class 
import java.util.*; 
  
class GFG { 
      
    // Driver code 
    public static void main(String[] args) { 
  
    // creating calendar objects 
    Calendar cal_obj1 = Calendar.getInstance(); 
    Calendar cal_obj2 = Calendar.getInstance(); 
  
    // displaying the current date 
    System.out.println("Current date is : " + 
                        cal_obj1.getTime()); 
  
    // changing year in cal_obj2 calendar 
    cal_obj2.set(Calendar.YEAR, 2010); 
      
    // displaying the year 
    System.out.println("Year is " +  
                        cal_obj2.get(Calendar.YEAR)); 
  
    // check if calendar date is equal to current date 
    System.out.println("Result : " +  
                        cal_obj1.equals(cal_obj2)); 
    } 
}


輸出:
Current date is : Thu Mar 01 09:39:30 UTC 2018
Year is 2010
Result : false


相關用法


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