2014-11-04 55 views
2

如何檢查一段時間(包括兩個時間值(開始和結束))是否通過例如午夜?如何檢查一段時間是否經過了確切的時間戳?

我試着去使用LocalDateTime類,但似乎無法找到任何有用的有..

+2

'if(start midnight)'(僞代碼)怎麼辦?提示:使用方法'isBefore'和'isAfter'。 – Thomas 2014-11-04 10:47:13

+0

所有時間戳在午夜之前和午夜之後。 – aioobe 2014-11-04 10:48:24

+0

檢查JodaTime或日曆以獲得日期時間方便。 – Dmytro 2014-11-04 10:51:47

回答

0

這是我能拿出最好的:

public static boolean passesTime(LocalDateTime start, 
           LocalDateTime end, 
           LocalTime time) { 

    // If the duration is more than a day, any time will be passed. 
    if (Duration.between(start, end).toDays() >= 1) 
     return true; 

    // Otherwise, the time has to be passed on the start day... 
    LocalDateTime timeOnStartDay = LocalDateTime.of(start.toLocalDate(), time); 
    if (timeOnStartDay.isAfter(start) && timeOnStartDay.isBefore(end)) 
     return true; 

    // or on the end day. 
    LocalDateTime timeOnEndDay = LocalDateTime.of(end.toLocalDate(), time); 
    if (timeOnEndDay.isAfter(start) && timeOnEndDay.isBefore(end)) 
     return true; 

    return false; 
} 

java.time API測試。如果您使用Joda時間,代碼應該相似(如果不相同)。

相關問題