[英]How can I compare two hours in java?
I want to calculate restaurant's opened hours.我想计算餐厅的营业时间。 I have two string, for example:
我有两个字符串,例如:
String start_hour = "09:00";
String end_hour = "18:00";
And current hour for example:和当前时间例如:
Calendar now = Calendar.getInstance();
String current_hour = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE);
I calculate open hours with this method:
public boolean isRestaurantOpenNow() {
try {
Calendar now = Calendar.getInstance();
String current_hour = now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE);
String st_hour = "09:00";
String en_hour = "18:00";
@SuppressLint("SimpleDateFormat") final SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date sth = null;
sth = format.parse(st_hour);
Date enh = format.parse(en_hour);
Date nowh = format.parse(current_hour );
if (nowh != null) {
if (nowh.before(enh) && nowh.after(sth)) {
// restaurant is open
return true;
} else {
// restaurant is close
return false;
}
}
} catch (ParseException ignored) {
}
return false;
}
But I have some problem with that.但我对此有一些问题。 This method working wrong when start_hour is "13:00" and end_hour "05:00".
当 start_hour 为 "13:00" 和 end_hour "05:00" 时,此方法会出错。 Because 05:00 hour from next day.
因为从第二天 05:00 开始。 How can I solve this problem?
我怎么解决这个问题?
instead of代替
nowh.before(enh) && nowh.after(sth)
use用
nowh.before(enh) && nowh.after(sth) && sth.before(enh)
|| enh.before(sth) && !(nowh.before(enh) && nowh.after(sth))
Apart from that I think Calendar class is supposed to be used differently I assume...除此之外,我认为 Calendar 类应该以不同的方式使用,我认为......
public boolean isRestaurantOpenNow() {
LocalTime startHour = LocalTime.parse("13:00");
LocalTime endHour = LocalTime.parse("05:00");
LocalTime currentHour = LocalTime.now(ZoneId.systemDefault());
if (startHour.isBefore(endHour)) { // Both are on the same day
return currentHour.isAfter(startHour) && currentHour.isBefore(endHour);
} else { // end is on the next day
return currentHour.isBefore(endHour) || currentHour.isAfter(startHour) ;
}
}
Trying it just now (21:20 in my time zone):刚刚尝试(在我的时区 21:20):
System.out.println(isRestaurantOpenNow());
Output was:输出是:
true
真的
java.time works nicely on both older and newer Android devices. java.time 在较旧和较新的 Android 设备上都能很好地工作。 It just requires at least Java 6 .
它只需要至少Java 6 。
org.threeten.bp
with subpackages.org.threeten.bp
导入日期和时间类。java.time
was first described. java.time
。java.time
to Java 6 and 7 (ThreeTen for JSR-310). java.time
到 Java 6 和 7 的 backport(ThreeTen for JSR-310)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.