Java 不同格式的日期对象不';不相等
我有一个比较两个日期对象的代码。它们以不同的格式存储日期,但具有相同的日期含义Java 不同格式的日期对象不';不相等,java,date,java-7,Java,Date,Java 7,我有一个比较两个日期对象的代码。它们以不同的格式存储日期,但具有相同的日期含义 public class DateTest { public static void main(String[] args) { compareDate(); } public static void compareDate() { try { DateFormat df = new SimpleDateFormat("EEE MMM
public class DateTest {
public static void main(String[] args) {
compareDate();
}
public static void compareDate() {
try {
DateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'ICT' yyyy");
Date date = df.parse("Thu Jan 22 03:16:26 ICT 2015");
System.out.println(date.toString());
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date2 = df2.parse("2015-01-22 03:16:26.723");
System.out.println(date2.toString());
System.out.println(date.after(date2));
System.out.println(date2.after(date));
System.out.println(date2.equals(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
我的机器的输出提供:
Thu Jan 22 03:16:26 ICT 2015
Thu Jan 22 03:16:26 ICT 2015
false
true
false
这显然表明两个日期相等,但为什么date2.after(Date)返回true
如果这是一个基本问题,请原谅。日期类的名称可能有点混淆,因为它不代表“日期”(一天),而是一个精确的时间戳 您的
date2
更晚,因为它包含723毫秒(另一个没有,所以它们是000毫秒)
您用来打印它的格式并没有显示出来。日期类的名称可能有点混淆,因为它不代表“日期”(一天),而是一个精确的时间戳 您的
date2
更晚,因为它包含723毫秒(另一个没有,所以它们是000毫秒)
您用于打印的格式并不显示这一点。您可以查看java.util.Date.after(Date)的实现,它比较两个日期的毫秒部分
/**
* Tests if this date is after the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant represented
* by this <tt>Date</tt> object is strictly later than the
* instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
您可以查看java.util.Date.after(Date)的实现,它比较两个日期的毫秒部分
/**
* Tests if this date is after the specified date.
*
* @param when a date.
* @return <code>true</code> if and only if the instant represented
* by this <tt>Date</tt> object is strictly later than the
* instant represented by <tt>when</tt>;
* <code>false</code> otherwise.
* @exception NullPointerException if <code>when</code> is null.
*/
public boolean after(Date when) {
return getMillisOf(this) > getMillisOf(when);
}
毫秒感知如果你看一看每个日期等于
date
=1421856986000
和date2
=1421856986723
的毫秒数,你为什么期望03:16:26.723
不晚于03:16:26
?毫秒感知看看每个日期等于date
=1421856986000
和date2
=1421856986723
的毫秒数,有毫秒的差异。你为什么期望03:16:26.723
不晚于03:16:26
?