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


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


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

用法:

public boolean equals(Object obj)

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


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

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

// Java code to illustrate equals() method 
  
import java.text.*; 
import java.util.*; 
  
public class SimpleDateFormat_Demo { 
    public static void main(String[] args) 
        throws InterruptedException, ParseException 
    { 
        // Initializing the first formatter 
        SimpleDateFormat SDFormat1 
            = new SimpleDateFormat(); 
  
        // Initializing the second formatter 
        SimpleDateFormat SDFormat2 
            = new SimpleDateFormat(); 
  
        // Displaying both the Formats 
        Date date = new Date(); 
        String str_Date1 
            = SDFormat1.format(date); 
        System.out.println("First: "
                           + (str_Date1)); 
  
        String str_Date2 
            = SDFormat2.format(date); 
        System.out.println("Second: "
                           + (str_Date2)); 
  
        // Comparing both the objects 
        System.out.println("Equality: "
                           + SDFormat1.equals(SDFormat2)); 
    } 
}
輸出:
First: 1/30/19 9:59 AM
Second: 1/30/19 9:59 AM
Equality: true

示例2:

// Java code to illustrate equals() method 
  
import java.text.*; 
import java.util.*; 
  
public class SimpleDateFormat_Demo { 
    public static void main(String[] args) 
        throws InterruptedException, ParseException 
    { 
        // Initializing the first formatter 
        SimpleDateFormat SDFormat1 
            = new SimpleDateFormat(); 
  
        // Defining the SDFormat 
        SDFormat1.applyPattern("MMM"); 
  
        // Initializing the second formatter 
        SimpleDateFormat SDFormat2 
            = new SimpleDateFormat(); 
  
        // Displaying both the Formats 
        Date date = new Date(); 
        String str_Date1 
            = SDFormat1.format(date); 
        System.out.println("First:  
                           + (str_Date1)); 
  
        String str_Date2 
            = SDFormat2.format(date); 
        System.out.println("Second: "
                           + (str_Date2)); 
  
        // Comparing both the objects 
        System.out.println("Equality: "
                           + SDFormat1.equals(SDFormat2)); 
    } 
}
輸出:
First: Jan
Second: 1/30/19 10:00 AM
Equality: false


相關用法


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