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


Java DateFormat equals()用法及代碼示例


DateFormat類的equals()方法用於比較兩個DateFormat對象。如果此DateFormat等於傳遞的對象,則該方法返回True,否則返回False。

用法:

public boolean equals(Object obj)

參數:該方法采用Object類型的一個參數obj,表示要與此DateFormat對象進行比較的對象。


返回值:如果兩個對象相等,則該方法返回布爾True,否則返回False。

以下示例程序旨在說明DateFormat的equals()方法的用法:
示例1:

// Java code to illustrate equals() method 
  
import java.text.*; 
import java.util.*; 
  
public class DateFormat_Demo { 
    public static void main(String[] args) 
    { 
        // Initializing the first formatter 
        DateFormat DFormat1 
            = DateFormat.getDateInstance(); 
  
        // Initializing the second formatter 
        DateFormat DFormat2 
            = DateFormat.getDateInstance(); 
  
        // Displaying both the Formats 
        Date date = new Date(); 
        String str_Date1 
            = DFormat1.format(date); 
        System.out.println("First: "
                           + (str_Date1)); 
  
        String str_Date2 
            = DFormat2.format(date); 
        System.out.println("Second: "
                           + (str_Date2)); 
  
        // Comparing both the objects 
        System.out.println("Equality: "
                           + DFormat1.equals(DFormat2)); 
    } 
}
輸出:
First: Mar 27, 2019
Second: Mar 27, 2019
Equality: true

示例2:

// Java code to illustrate equals() method 
  
import java.text.*; 
import java.util.*; 
  
public class DateFormat_Demo { 
    public static void main(String[] args) 
    { 
        // Initializing the first formatter 
        DateFormat DFormat1 
            = DateFormat.getDateInstance(); 
  
        // Initializing the second formatter 
        DateFormat DFormat2 
            = DateFormat.getTimeInstance(); 
  
        // Displaying both the Formats 
        Date date = new Date(); 
        String str_Date1 
            = DFormat1.format(date); 
        System.out.println("First: "
                           + (str_Date1)); 
  
        String str_Date2 
            = DFormat2.format(date); 
        System.out.println("Second: "
                           + (str_Date2)); 
  
        // Comparing both the objects 
        System.out.println("Equality: "
                           + DFormat1.equals(DFormat2)); 
    } 
}
輸出:
First: Mar 27, 2019
Second: 11:04:25 AM
Equality: false

參考: https://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#equals(java.lang.Object)



相關用法


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