I'm using the code below to check if an hour is between two other specific hours:
String openHour = "08:00 AM";
String currentHour = "10:00 PM";
String closeHour = "11:00 PM"; //Change to 02:00 AM doesn't work!!!
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date openHourDate = format.parse(openHour);
Date currentHourDate = format.parse(currentHour);
Date closeHourDate = format.parse(closeHour);
Calendar openCalendar = Calendar.getInstance();
openCalendar.setTime(openHourDate);
Calendar currentCalendar = Calendar.getInstance();
currentCalendar.setTime(currentHourDate);
Calendar closeCalendar = Calendar.getInstance();
closeCalendar.setTime(closeHourDate);
Date open = openCalendar.getTime();
Date current = currentCalendar.getTime();
Date close = closeCalendar.getTime();
if (current.after(open) && current.before(close)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
If the currentHour
is "10:00 PM"
as you see in my code, everything works fine but if I change the change it to "02:00 AM"
, the code doesn't work as expected even if the currentHour
is between 08:00 AM
and 02:00 AM
. How to solve this?
Here is a solution using LocalTime
that also correctly handles current and closing time being after midnight.
String openHour = "08:00 AM";
String currentHour = "01:00 PM";
String closeHour = "02:00 AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "hh:mm a" , Locale.US );
LocalTime openTime = LocalTime.parse(openHour, formatter);
LocalTime currentTime = LocalTime.parse(currentHour, formatter);
LocalTime closeTime = LocalTime.parse(closeHour, formatter);
boolean isOpen = false;
if (closeTime.isAfter(openTime)) {
if (openTime.isBefore(currentTime) && closeTime.isAfter(currentTime)) {
isOpen = true;
}
} else if (currentTime.isAfter(openTime) || currentTime.isBefore(closeTime)) {
isOpen = true;
}
if (isOpen) {
System.out.println("We are open");
} else {
System.out.println("We are closed");
}