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