在 java.time.LocalTime 之间(第二天)

between java.time.LocalTime (next day)

请建议是否有 API 支持来确定我的时间是否在 2 LocalTime 个实例之间,或者建议不同的方法。

我有这个实体:

 class Place {
   LocalTime startDay;
   LocalTime endDay;
 }

存储工作日的开始和结束时间,即从“9:00”到“17:00”,或者从“22:00”到“5:00”的夜总会。

我需要实施一个 Place.isOpen() 方法来确定该地点在给定时间是否开放。

这里简单的isBefore/isAfter不行,因为我们还要判断结束时间是不是第二天

当然,我们可以比较开始和结束时间并做出决定,但我想要一些没有额外逻辑的东西,只是一个简单的between()调用。如果 LocalTime 不足以满足此目的,请提出其他建议。

如果我没理解错的话,你需要根据收盘时间是和开盘时间是当天(9-17)还是次日(22-5)分两种情况。

它可以简单地是:

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

这对我来说看起来更干净:

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

我重构了@assylias 的回答,所以我使用 int 而不是本地时间,因为我从 api int 整数格式

获取开盘和收盘时间
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);
    }
}