📜  Java中的 DateFormat equals() 方法及示例

📅  最后修改于: 2022-05-13 01:55:02.258000             🧑  作者: Mango

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: Java Java.lang.Object)