2014-04-01 41 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,但恰巧第二个日期是第一个具有几纳秒之后。