Between java.time.LocalTime (the next day)

Please suggest if there is API support to determine if my time is between 2 LocalTime instances or suggest a different approach.

I have this object:

  class Place { LocalTime startDay; LocalTime endDay; } 

which stores the start and end time of the working day, that is, from 9:00 to 17:00 or a night club from 22:00 to 5:00.

I need to implement the Place.isOpen() method, which determines whether a place is currently open.

The simple isBefore / isAfter does not work here, because we also need to determine if there will be an end time the next day.

Of course, we can compare the start and end times and make a decision, but I want something without additional logic, just a simple call between() . If LocalTime not enough for this purpose, suggest another.

+9
source share
3 answers

If I understand correctly, you need to do two cases, depending on whether the closing time is on the same day as the opening time (9-17) or the next day (22-5).

It could be simple:

 public static boolean isOpen(LocalTime start, LocalTime end, LocalTime time) { if (start.isAfter(end)) { return !time.isBefore(start) || !time.isAfter(end); } else { return !time.isBefore(start) && !time.isAfter(end); } } 
+11
source

This looks cleaner for me:

  if (start.isBefore(end)) { return start.isBefore(date.toLocalTime()) && end.isAfter(date.toLocalTime()); } else { return date.toLocalTime().isAfter(start) || date.toLocalTime().isBefore(end); } 
0
source

I reorganized @assylias answer, so I use int instead of local time, since I get opening and closing hours from integer api int format

 public static boolean isOpen(int start, int end, int time) { if (start>end) { return time>(start) || time<(end); } else { return time>(start) && time<(end); } } public static boolean isOpen(int start, int end) { SimpleDateFormat sdf = new SimpleDateFormat("HH"); Date resultdate = new Date(); String hour = sdf.format(resultdate); int time = Integer.valueOf(hour); if (start>end) { return time>(start) || time<(end); } else { return time>(start) && time<(end); } } 
0
source

Source: https://habr.com/ru/post/1242292/


All Articles