The answer by Vimukthi_R is helpful in showing you the right library class and methods to use and is almost correct. So my version is similar, but I would like to show you a few twists.
LocalTime minTime = LocalTime.of(6, 0);
LocalTime maxTime = LocalTime.of(22, 0);
String timeStart = "08:00";
String timeEnd = "21:00";
LocalTime startDay = LocalTime.parse(timeStart);
LocalTime endDay = LocalTime.parse(timeEnd);
if (startDay.isBefore(minTime)
|| endDay.isBefore(startDay)
|| endDay.isAfter(maxTime)) {
System.out.print("no");
} else {
System.out.print("passed");
}
Since you want to accept start and end times in the interval frmo 6 to 22 inclusive, isBefore
and isAfter
don’t really give you the exact answer. We would have needed methods isBeforeOrOn
and isOnOrAfter
, but they don’t exist. Rather than writing auxiliary methods for that purpose, I am turning the whole logic upside-down: if the start time is before 6 or the end time after 22, the validation fails.
For defining 6 and 22 as LocalTime
objects parsing strings works, but my taste is more for the of
method (please make your own pick).
For parsing we don’t need a formatter since your strings are in the standard ISO 8601 format that LocalTime
parses as its default. One may of course prefer the formatter since it makes the format explicit in the code. Again pick your own preference.
I was assuming that end time could not be before start time, which simplified the condition to three sub-conditions instead of four. If you didn’t want this, I am trusting you to write out the four subconditions.
I am not sure whether my comparison of time is correct
No, your comparison was not correct. In Java you can use >=
and <=
for comparing numbers, but not strings or or other objects like LocalTime
. Also, as Johannes Kuhn said in a comment, you cannot parse a string like 08:00
into an integer. FallingCoder said the rest in a comment:
Additionally, single quotation marks are exclusively for Characters.
Not Strings.
Link: Oracle tutorial: Date Time explaining how to use java.time.