Time comparison
With Java 8+, you can use the new Java time API:
to parse the time:
LocalTime time = LocalTime.parse("11:22")
to do date comparisons, you have
LocalTime::isBefore
andLocalTime::isAfter
- note that these methods are strict
So you problem would be as simple as:
public static void main(String[] args) {
LocalTime time = LocalTime.parse("11:22");
System.out.println(isBetween(time, LocalTime.of(10, 0), LocalTime.of(18, 0)));
}
public static boolean isBetween(LocalTime candidate, LocalTime start, LocalTime end) {
return !candidate.isBefore(start) && !candidate.isAfter(end); // Inclusive.
}
For inclusive beginning but exclusive ending (half-open), use this line.
return !candidate.isBefore(start) && candidate.isBefore(end); // Exclusive of end.
Java doesn't (yet) have a good built-in Time
class (it has one for JDBC queries, but that's not what you want).
One option would be use the JodaTime APIs and its LocalTime class.
Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date
comparison functions to see if it is before or after some other time:
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");
try {
Date userDate = parser.parse(someOtherDate);
if (userDate.after(ten) && userDate.before(eighteen)) {
...
}
} catch (ParseException e) {
// Invalid date was entered
}
Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:
Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
String hourString = m.group(1);
String minuteString = m.group(2);
int hour = Integer.parseInt(hourString);
int minute = Integer.parseInt(minuteString);
if (hour >= 10 && hour <= 18) {
...
}
}
It really all depends on what you are trying to accomplish.