如何确定具体时间是否在给定范围之间?

时间:2012-05-07 20:40:12

标签: java

问题:我有一个包含小时的列表,例如: 8时15分00秒 八点45分00秒 09:00:00 12:00:00 ... 应用程序允许用户预约特定时间,我们:8:15:00,每次会议需要半小时。

问题:如何确定预约是否需要这样的插槽?我知道Calendar类在before()之前有()后面的方法,但它没有解决我的问题。我的意思是如果在12:00和另一个在12:00预约,如何防止在12:15再制作一个?

编辑:

我尝试过使用之前提到的方法,例如:

Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00

if(user.after(cal1)&& user.before(cal2)){
... // do sth
}

3 个答案:

答案 0 :(得分:5)

检查要检查的日期是否在提供的日期之间:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();

要预定一个确定的小时,我会做一个有两个日期的课程和一个方法来检查:

public class Appointment{

 private Date start;
 private Date end;

 public boolean isBetween(Date toCheck){....}

}

然后,您只需执行Schedule类扩展ArrayList,添加方法isDateAvailable(Date toCheck),迭代约会列表并检查没有人冲突。

答案 1 :(得分:1)

我有某种约会类,包括开始时间戳和持续时间,开始时间和结束时间。然后,在向计划添加新约会时,检查具有新约会之前的开始时间的约会是否未在建议的新约会的开始时间内运行。

答案 2 :(得分:1)

你如何做到这一点具体取决于你如何存储你的数据,格式等,但通常你要做的只是检查在请求的时间到请求的时间之间的任何时间是否有预约+要求的长度。

// Example (using int time(1 = 1 minute), assuming that appointments can only be at 15min intervals)
boolean isHalfHourTimeSlotAvaliable(int time) {
    for (int i = 0; i < appointments.size(); i++) {
        if (appointments.get(i).time == time || appointments.get(i).time == time + 15) {
            return false;
        }
    }
    return true;
}