2014-04-01 38 views
1

我想比較兩個日期。這裏是我的日期比較的代碼...java日期比較幫助要求

Date dbLastModified = getBulletinBarMessageLastModified(); 
Date bulletinBarMessageLastModified = bulletinBarForm.getLastModified(); 

if (dbLastModified.after(bulletinBarMessageLastModified)){ 
    throw new ReportingManagerOptimisticLockingException(optimisticLockingMessage); 
} 

public Date getBulletinBarMessageLastModified() { 
    Timestamp lastModifiedTimestamp = getJdbcTemplate().queryForObject(BULLETIN_BAR_MSG_LAST_MODIFIED_SQL,Timestamp.class); 
    Date lastModifiedDate = new Date(lastModifiedTimestamp.getTime()); 
    return lastModifiedDate; 
} 

...

dbLastModified - Tue Apr 01 22:29:04 EST 2014 
bulletinBarMessageLastModified - Tue Apr 01 22:29:04 EST 2014 

我很困惑,爲什麼即使在一些日期是看似相等的(如二)爲什麼我的代碼拋出ReportingManagerOptimisticLockingException異常,暗示其中一個是之後的。我對日期比較的理解是錯誤的嗎?

+4

日期以毫秒爲單位存儲,所以它們在毫秒中可能實際上是不同的,儘管它們看起來相同。 –

+2

時間戳不能可靠地用作版本數據類型。對於客戶端上的一個時間戳解析,DB操作系統和數據庫本身可能會有所不同。即使有相當高的分辨率,也會出現兩次更新在同一時刻發生並且未被檢測爲不同版本的情況。 – Ralf

+0

是的。你們是對的。謝謝.....第一次約會:2014-04-02T08:35:12.000 + 1100 ......第二次約會:2014-04-02T08:35:12.015 + 1100 – Richie

回答

2

Timestamp.getTime()認爲納秒以及。 所以即使toString()返回相同的輸出,實際上還有一個納米的區別。

java.util.Date只涉及毫秒

+0

不可思議。 '處理日期'後,所以它只會比較毫秒。它看起來有一個毫秒的差異,但因爲OP將日期打印到最近的秒鐘,所以不會顯示。 「TimeStamp」中的納秒與此無關。 –

1

Here

你可以閱讀以下內容:

公共布爾後

(年月日時)

Tests if this date is after the specified date. 

Parameters: 
    when - a date. 
Returns: 
    true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false 

否則。拋出: NullPointerException - 如果when爲null。現在

,它要麼是一個Java錯誤或dbLastModified真的bulletinBarMessageLastModified有幾納秒之後。

如果下面是false

dbLastModified.after(dbLastModified) 

那麼它可能不是一個Java bug,但恰巧第二個日期是第一個具有幾納秒之後。