2014-11-04 90 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时间,代码应该相似(如果不相同)。

相关问题