user471011
user471011

Reputation: 7374

Java. Check time range. How?

For example, I have input parameter this format: "04:00-06:00" or "23:00-24:00". Type of parameter - String.

And in my method I must check, that time range in input parameter NOT before current time. How I can do it?

More details:

input time range: "12:00-15:00"

current time: 16:00.

In this case, method must return false.

Another example:

input time range: "10:30-12:10"

current time: 09:51.

method must return true.

Can you please give me some idea or algorithm? How I can implement this method?

Upvotes: 1

Views: 7879

Answers (2)

awiebe
awiebe

Reputation: 3836

Date currentDate = new Date();
Date maxDate;
Date minDate;

//Parse range to two substrings
//parse two substrings to [HH, MM]
//for HH && MM parseInt()
//
minDate= new Date.SetHour(HH); minDate.SetMinute(MM);
//repeat for max date

if(currentDate.Before(maxDate) && currentDate.After(minDate))
{
return true;
}
else
return false;

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120506

First off, you should probably just learn to use Joda time.

That said, since the times are all zero padded, you can just compare strings lexically.

public static boolean inRange(String time, String range) {
  return time.compareTo(range.substring(0, 5)) >= 0
      && time.compareTo(range.substring(6)) <= 0;
}

It's good practice to fail fast on malformed inputs.

private static final Pattern VALID_TIME = Pattern.compile("[012][0-9]:[0-5][0-9]");
private static final Pattern VALID_RANGE = Pattern.compile("[012][0-9]:[0-5][0-9]-[012][0-9]:[0-5][0-9]");

and then put an assert at the top of inRange:

assert VALID_TIME.matcher(time).matches() : time
assert VALID_RANGE.matcher(range).matches() : range

EDIT:

If you really need to represent the current time as a Date, then you should compare it this way:

 public final class Range {
   /** Inclusive as minutes since midnight */
   public final int start, end;
   public Range(int start, int end) {
     assert end >= start;
   }

   /** @param time in minutes since midnight */
   public boolean contains(int time) {
     return start <= time && time <= end;
   }

   public static Range valueOf(String s) {
     assert VALID_RANGE.matcher(s).matches() : s;
     return new Range(minutesInDay(s.substring(0, 5)),
                      minutesInDay(s.substring(6));
   }

   private static int minutesInDay(String time) {
     return Integer.valueOf(time.substring(0, 2)) * 60
         + Integer.valueOf(time.substring(3));
   }
 }

Use Range.valueOf to convert from a String, convert your Date to a number of minutes since midnight in whatever timezone you like using whatever calendar implementation you like, and then use Range.contains.

Upvotes: 5

Related Questions