【问题标题】:How to traverse between a given time (i.e.11:00 am) and another time (i.e. 1:00 pm) in java?java - 如何在Java中的给定时间(即上午11:00)和另一个时间(即下午1:00)之间遍历?
【发布时间】:2019-05-18 06:11:15
【问题描述】:

我正在用 Java 为餐厅制作在线预订系统。我想知道是否保留了一张桌子。我想出了这段代码。

我不确定如何实现这个逻辑。

public class Services {

    public void reserveTable(String tableSize ,int time_limit){         

        String starting_time = "11:00 am";
        String ending_time = "1:00 pm";
        String current_time = "12:00 pm"; //time at which new order arrived
        boolean reserved = false

        for (String start = "11:00 am"; start <= ending_time; start ++){
            if (current_time == start){
                reserved = true;
            }
        }        
   }         
}

【问题讨论】:

  • 您需要查看LocalTime(可能还有LocalDateTime),Date and Time Classes 可能是一个不错的起点

标签: java


【解决方案1】:

您可以使用DateTimeFormatter 将您的时间字符串解析为LocalTimes,然后检查current 是否介于startend 之间:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("h:mm a")
            .toFormatter(Locale.ENGLISH);
    LocalTime start = LocalTime.parse("11:00 am", formatter);
    LocalTime end = LocalTime.parse("1:00 pm", formatter);
    LocalTime current = LocalTime.parse("12:00 pm", formatter);

    boolean reserved = false;
    if (current.isAfter(start) && current.isBefore(end)) {
        reserved = true;
    }

请注意,如果开始和结束跨越午夜,这将不起作用。例如start 是晚上 11 点,end 是凌晨 2 点。凌晨 1 点的 current 不会导致 reserved 设置为 true。要使这种情况有效,您需要一个日期。

【讨论】:

  • 其实你不需要一个日期来处理午夜,看我的解决方案in this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多