Java DateFormat equals()方法及实例

Java DateFormat equals()方法及实例

DateFormat 类的 equals() 方法是用来比较两个DateFormat对象。如果这个DateFormat等于所传递的对象,该方法返回True,否则返回False。

语法

public boolean equals(Object obj)

参数: 该方法需要一个对象类型的参数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)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程