簡體   English   中英

如何檢查某個時間段是否經過了確切的時間戳?

[英]How to check if a certain period of time passes an exact timestamp?

我如何檢查一段時間(由兩個時間時間值(開始和結束)組成)是否經過了例如午夜?

我試圖使用LocalDateTime類,但似乎找不到任何有用的方法。

這是我能想到的最好的方法:

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時間,則代碼應相似(如果不相同)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM