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". Because 05:00 hour from next day. 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...