不同格式的日期对象不相等

时间:2015-01-22 03:45:56

标签: java date java-7

我有这个代码比较两个Date对象。它们以不同的格式存储日期,但它们的含义相同。

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

它显然表明两个Date是等于但是为什么date2.after(date)返回true?

如果这是一个基本问题,请原谅。

2 个答案:

答案 0 :(得分:4)

Date类可能有点混乱,因为它不代表" date" (一天),但确切的时间戳。

你的date2之后是因为它包含了723毫秒(另一个没有,所以它们都是000)。

用于打印它的格式不会显示。

答案 1 :(得分:1)

你可以查看java.util.Date.after(Date)的实现,它比较了两个日期的millis部分。

/**
     * 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);
    }