在Java中检查另外两个日期之间的日期时得到不正确的结果 [英] Getting incorrect result when checking a date between two other dates in Java

查看:57
本文介绍了在Java中检查另外两个日期之间的日期时得到不正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码检查一个小时是否在其他两个特定小时之间:

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!");
}

如果您在代码中看到的currentHour"10:00 PM",则一切正常,但如果将更改更改为"02:00 AM",即使currentHour08:00 AM02:00 AM.该如何解决?

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");
}

这篇关于在Java中检查另外两个日期之间的日期时得到不正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆