JodaTime - check if LocalTime is now and now before another LocalTime

I am trying to check if the current time is after the start LocalTimeand before the other end LocalTime, which is the start time plus 11 hours. This works great if the start time is 11:00 (end time is 22:00). However, when I try to compare the start time at 16:00 and the end time at 03:00, it currentTime.isBefore(endTime)will never be logged, but it should be.

LocalTime currentTime = LocalTime.now(); //21:14
LocalTime startTime = new LocalTime( 16, 00, 0, 0);
LocalTime endTime = startTime.plusHours(11); //03:00 Midnight

    if(currentTime.isAfter(startTime)){
        Log.v("Test", "After startTime");
    }

    if(currentTime.isBefore(endTime)){
        Log.v("Test", "Before endTime");
    }

Any ideas how to solve this problem?

+4
source share
2 answers

, startTime endTime (.. endTime startTime). , "" , , , .

public boolean isWithinInterval(LocalTime start, LocalTime end, LocalTime time) {
    if (start.isAfter(end)) {
        return !isWithinInterval(end, start, time);
    }
    // This assumes you want an inclusive start and an exclusive end point.
    return start.compareTo(time) <= 0 &&
           time.compareTo(end) < 0;
}

, , , , , ( ), . , :

public boolean isWithinInterval(LocalTime start, LocalTime end, LocalTime time) {
    if (start.isAfter(end)) {
        // Return true if the time is after (or at) start, *or* it before end
        return time.compareTo(start) >= 0 ||
               time.compareTo(end) < 0;
    } else {
        return start.compareTo(time) <= 0 &&
               time.compareTo(end) < 0;
    }
}

( , compareTo, , . .)

, :

import org.joda.time.LocalTime;

public class Test {
    public static void main(String[] args) {
        LocalTime morning = new LocalTime(6, 0, 0);
        LocalTime evening = new LocalTime(18, 0, 0);
        LocalTime noon = new LocalTime(12, 0, 0);
        LocalTime midnight = new LocalTime(0, 0, 0);
        System.out.println(isWithinInterval(morning, evening, noon)); // true
        System.out.println(
            isWithinInterval(morning, evening, midnight)); // false
        System.out.println(
            isWithinInterval(evening, morning, noon)); // false
        System.out.println(
            isWithinInterval(evening, morning, midnight)); // true
    }

    public static boolean isWithinInterval(LocalTime start, 
                                           LocalTime end,
                                           LocalTime time) {
        if (start.isAfter(end)) {
            // Return true if the time is after (or at) start,
            // *or* it before end
            return time.compareTo(start) >= 0 ||
                time.compareTo(end) < 0;
        } else {
            return start.compareTo(time) <= 0 &&
                time.compareTo(end) < 0;
        }
    }
}
+9

LocalTime - , – a .
, .

, , , DST.

+3

Source: https://habr.com/ru/post/1531042/


All Articles