2012-12-17 95 views
0

比較喬達LocalDateTime和DateTime我想寫將採取LocalDateTimeDateTime的方法(使用約達1.3),並確定它們是否彼此的30分鐘內。這是我能拿出最好的,但我知道必須有一個更好/清潔/更有效的方式:範圍內

public boolean isWithin30MinsOfEachOther(LocalDateTime localDateTime, DateTime dateTime) { 
    return (
     localDateTime.getYear() == dateTime.getYear() && 
     localDateTime.getMonthOfYear() == dateTime.getMonthOfYear() && 
     localDateTime.getDayOfMonth() == dateTime.getDayOfMonth() && 
     localDateTime.getHourOfDay() == dateTime.getHourOfDay() && 
     Math.abs((localDateTime.getMinuteOfHour() - dateTime.getMinuteOfHour())) <= 30 
    ); 
) 

何況我不認爲這個工程如果說,localDateTime是2012年12月31日23:58:00和dateTime是2013年1月1日00:01:00。兩個不同的月份和日期的開始/結束是同一件事。有什麼建議麼?提前致謝。

回答

1

您是否嘗試過使用Duration類?

作爲一個例子:

Duration myDuration=new Duration(localDateTime.toDateTime(), dateTime); 
    return Math.abs(myDuration.getMillis())<=30*60*1000; 
+1

由於@Tomas Narros,然而,這是約達1.3和'getStandardMinutes'不可用的API中。另外,我不能簡單地更新到更現代的版本,我堅持1.3。 – IAmYourFaja

+0

如果我使用'getMillis()'來代替然後除以1,000,該怎麼辦? – IAmYourFaja

+1

@ HeineyBehinds真實,修復它。請檢查我的版本(除以60和1000,或更清晰,將30乘以60和1000的倍數)... –

0

你可以嘗試

return Math.abs(localDateTime.getLocalMillis() 
       - dateTime.toLocalDateTime().getLocalMillis()) < 30 * 60 * 1000;