2012-08-01 64 views
0

这里不工作是我的代码:Java的日期时间之前预期生产

long treatmentTimeBeginDay; 
if (effectiveBegin.after(businessClosing)) { 
    LOGGER.debug("Compute treatment time for beginDay = 0: the effective begin {} is after business closing {}", 
          config.formatLogDate(effectiveBegin),config.formatLogDate(businessClosing)); 
    treatmentTimeBeginDay = 0; 
} else { 
    LOGGER.debug("Compute treatment time for beginDay between {} and {}",config.formatLogDate(effectiveBegin),config.formatLogDate(businessClosing)); 
    treatmentTimeBeginDay = businessClosing.getTime() - effectiveBegin.getTime(); 
} 
Preconditions.checkState(treatmentTimeBeginDay >= 0 , "Internal bug! treatmentTimeBeginDay="+treatmentTimeBeginDay); 

effectiveBegin和businessClosing不为空,也番石榴先决条件检查,你可以看到它在日志...

它运行在大多数情况下,罚款,但在生产中,我们有这些错误:

致:java.lang.IllegalStateException:内部错误! treatmentTimeBeginDay = -852

我不给你堆/代码的其余部分,因为它应该是足够了... 唯一的例外是明确我的番石榴checkState呼吁提高。

我也有日志:

DEBUG [BusinessHoursUtils.java:257] llairie - 为beginDay计算处理时间 12年7月19日12年7月19日之间在下午8:00到8: 00 PM

(我不能有日志,米莉现在)


我想要了解的是。

如果我得到了我给你的日志,这意味着测试if (effectiveBegin.after(businessClosing))是错误的,所以effectiveBegin应该在businessClosing之前或等于。

在这种情况下,effectiveBegin时间戳应该低于businessClosing时间戳。

所以当我做businessClosing.getTime() - effectiveBegin.getTime();我期望有一个正数。

那么请有人能告诉我为什么我的异常消息中有-852毫秒?这怎么可能?


编辑:我怀疑一个棘手的情况下后/前法不会为毫秒工作,似乎这就是问题所在,因为我可以复制它在本地。

在运行时的2个日期为:

businessClosing = {[email protected]}"Thu Jul 19 20:00:00 CEST 2012" 
fastTime = 1342720800000 
cdate = null 

effectiveBegin = {[email protected]}"2012-07-19 20:00:00.999" 
nanos = 999000000 
fastTime = 1342720800000 
cdate = {[email protected]}"2012-07-19T20:00:00.000+0200" 

通过这些运行时对象,effectiveBegin.after(businessClosing) = false 如果我在DB effectiveBegin设定= 2012-07-19 20:00:01.000,1毫秒以后,则测试=真

在这两种情况下,我会希望有effectiveBegin.after(businessClosing) = true

看来,好像怀疑ametren,我的日期不同。

那么到底什么是问题? 我们是不是应该能够以毫秒的精度比较2日期实例? 即使它们是java.util.Date的子类?

+2

effectiveBegin的类型是什么? – ametren 2012-08-01 14:13:46

+1

没有其他一段代码修改'Date'吗?这个班应该被弃用,穿过碎纸机并烧毁。 – maaartinus 2012-08-01 14:15:43

+0

删除了不相关的番石榴和scjp标签。即使你使用番石榴的方法,你的问题不是关于番石榴 – 2012-08-01 14:25:45

回答

4

这里的问题是你混合时间戳和日期。 Timestamp.after(Date)仅比较Date组件的毫秒数,在您的示例中这两个组件均为1342720800000。 但是,Timestamp.getTime()也会考虑存储在时间戳内的纳秒(999000000ns = 999ms),并且将返回1342720800999。因此businessClosing.getTime() - effectiveBegin.getTime()将返回-999作为结果。

要解决此问题,可以将if语句修改为if(effectiveBegin.compareTo(businessClosing) > 0),或者可以在if语句之前将businessClosingDate转换为Timestamp

+0

如果时间戳只比较毫秒,为什么不能找到有效开始是在businessClosing之后,因为它有999个毫秒? – 2012-08-01 16:03:38

+0

因为当你调用'Timestamp.after(Date)'时,你有效地调用'Date.after(Date)'方法,它只考虑毫秒。 – 2012-08-01 16:10:52

+0

为答案增加了可能的解决方案 – 2012-08-02 09:24:19