between java.time.LocalTime (next day)

前端 未结 3 1801
孤街浪徒
孤街浪徒 2021-01-04 13:59

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

I have this entity:

相关标签:
3条回答
  • 2021-01-04 14:06

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

    It could simply be:

    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-04 14:22

    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 讨论(0)
  • 2021-01-04 14:32

    I have refactored @assylias answer so i use int instead of local time as i get open and close hour from api int integer 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 讨论(0)
提交回复
热议问题