# Time within a particular time interval

i’m trying to solve a seemingly simple problem, but just can’t quite get my mind around it.

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

Now given a third time – timeToTest – i need to find out if timeToTest lies between startTime and stopTime. There is no date information involved, other than just the times.

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

I’ve tried a solution with java.util.Date by converting the times to milliseconds using getTime(), but with any interval which rolls over the 24 hr barrier, the logic fails.

I’m trying to build a solution using Java – but i believe the logic is language independent.

So the simplest solution i could come up with, sticking to plain old 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 mistakes – would love to work and fix it.