- Time zone is crucial. Your verification makes no sense unless you know in which time zone you want the current time. For the reader’s sake, also specify it in your code.
- The date and time classes you use,
Date
, DateFormat
and SimpleDateFormat
, are not only long outdated, the last one in particular is also renowned for being troublesome to work with. Instead I recommend you use java.time
, the modern Java date and time API. This even furnishes a LocalTime
class, a time of day without a date, which matches your need much more precisely than Date
.
So your method is written clearly and tersely thus:
private static boolean verifyIfInside(String max, String min) {
LocalTime now = LocalTime.now(ZoneId.of("Europe/Budapest"));
LocalTime minHour = LocalTime.parse(min);
LocalTime maxHour = LocalTime.parse(max);
return ! (now.isBefore(minHour) || now.isAfter(maxHour));
}
Please substitute your desired time zone if it didn’t happen to be Europe/Budapest.
Since I understood that you wanted your range to be inclusive, and since isBefore
and isAfter
mean strictly before and after, I used a negation to test that the time is “not outside the range”.
I am furthermore exploiting the fact that your time format, 12:00:00
, agrees with ISO 8601, the format that the modern classes parse as their default, that is, without any explicit formatter. A potential downside is that validation of the time strings is weaker: parse()
will also accept 12:00
and 12:23:29.82376342
. If you need to reject these as errors, you do need an explicit formatter.
What went wrong in your code?
As far as I can tell, your code in the question is working correctly (if we just change hora1
to hour1
or the other way around, and hora2
too). You may have been confused about the order of the arguments. The following returns true if run between 12 and 18: verifyIfInside("18:00:00", "12:00:00")
. However, many would find it natural to write the call as verifyIfInside("12:00:00", "18:00:00")
, which returns false always. So it would almost surely be better to declare the method as verifyIfInside(String min, String max)
, that is, with min
before max
.
Another possibility is, of course, as I mentioned, that your JVM is using a different time zone from the one you think it is using. This would very likely give you unexpected results. The only way to be sure this is not the case is to specify explicitly which time zone it should use.