Time over a specified time interval

I am trying to solve a seemingly simple problem, but I just can’t understand it.

i has two times startTimeand stopTime, which can be considered to be in the format: hh:mm:ss[24hr format].

Now, given the third time - timeToTest- I need to find out if it is timeToTestbetween startTimeand stopTime. No date information other than time.

So, for example, if I have startTime= '22:30:00'and stopTime= '03:30:00', then for timeToTest= the '01:14:23'test should return true.

I tried a solution with java.util.Dateby converting time to milliseconds using getTime(), but with any interval that rolls across the 24-hour barrier, the logic fails.

I am trying to build a solution using Java - but I believe that the logic is language independent.

+3
source share
5 answers

So, the simplest solution that I could come up with, sticking to a simple old one java.util.Date, is shown below:

    String d1 = "21:00:00";
    String d2 = "04:00:00";
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    String dToTest = "16:00:00";
    boolean isSplit = false, isWithin = false;

    Date dt1 = null, dt2 = null,  dt3 = null;

    dt1 = sdf.parse(d1);
    dt2 = sdf.parse(d2);
    dt3 = sdf.parse(dToTest);

    isSplit = (dt2.compareTo(dt1) < 0);
    System.out.println("[split]: " +isSplit);

    if (isSplit)
    {
        isWithin = (dt3.after(dt1) || dt3.before(dt2));
    }
    else
    {
        isWithin = (dt3.after(dt1) && dt3.before(dt2));
    }

    System.out.println("Is time within interval? " +isWithin);

Feel free to point out any errors - would like to work and fix it.

+3
source

You have to add “day”, where “0” == current day, “1” == the next day, etc. So when stopTime == '03:30:00'should it be '27:30:00'(i.e. the next day).

In your case, if stopTime < startTime, add 86400 seconds.

+2
source

anirvan JodaTime:

public class TimeInterval24H {
    private final LocalTime start;
    private final LocalTime end;

    public TimeInterval24H(LocalTime start, LocalTime end) {
        this.start = start;
        this.end = end;
    }

    public TimeInterval24H(Date start, Date end) {
        this(new LocalTime(start), new LocalTime(end));
    }

    public boolean contains(Date test) {
        return contains(new LocalTime(test));
    }

    public boolean contains(LocalTime test) {
        if (isAccrossTwoDays()) {
            return (test.isAfter(getStart()) || test.isBefore(getEnd()));
        } else {
            return (test.isAfter(getStart()) && test.isBefore(getEnd()));
        }
    }

    boolean isAccrossTwoDays() {
        return getEnd().isBefore(getStart());
    }

    public LocalTime getStart() {
        return start;
    }

    public LocalTime getEnd() {
        return end;
    }

}
+2

:

  • , .

, , :

  • / ?
    • : - ,
    • : -

, , Joda Time, java.util. *, :)

+1

java.util.Calendar, before() after() . , , 5/18/2011. ( ), ?

0

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


All Articles