Skip to content
Advertisement

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.

Advertisement

Answer

So the simplest solution i could come up with, sticking to plain old java.util.Date, is shown below:

JavaScript

feel free to point out any mistakes – would love to work and fix it.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement