我正在使用下面的代码检查一个小时是否在其他两个特定小时之间:
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!");
}
如果您在代码中看到的currentHour
是"10:00 PM"
,那么一切正常,但是如果我将其更改为"02:00 AM"
,即使该代码无法正常工作,即使currentHour
在08:00 AM
和02:00 AM
之间。该如何解决?
答案 0 :(得分:4)
这是使用LocalTime
的解决方案,它也可以正确处理当前时间和午夜之后的关闭时间。
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");
}
答案 1 :(得分:2)
就像迈克尔·普拉特(Michael Platt)所建议的那样,只需要滚动一天即可
import java.util.*;
import java.text.*;
public class Foo {
public static void main(String[] args) throws Exception {
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);
if (closeCalendar.before(openCalendar)) {
closeCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
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!");
}
}
}