2012-08-01 65 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