当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。