Java SimpleDateFormat equals()方法及示例

Java SimpleDateFormat equals()方法及示例

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

语法

public boolean equals(Object obj)

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程