我有两个字符串变量" time1" &安培; "时间2&#34 ;.基本上,每个字符串变量本身都是一个时间范围。 要么" time1"介于" time2" OR " time2"介于" time1"之间。打印"不可用"。
示例案例1:
String time1 = "14:00 - 16:00"
String time2 = "15:00 - 16:00"
打印"不可用"
示例案例2:
String time1 = "14:00 - 17:00"
String time2 = "15:00 - 16:00"
打印"不可用"
示例案例3:
String time1 = "15:00 - 16:00"
String time2 = "14:00 - 17:00"
打印"不可用"
示例案例4:
String time1 = "15:00 - 16:00"
String time2 = "14:00 - 16:00"
打印"不可用"
示例案例5:
String time1 = "14:00 - 15:00"
String time2 = "15:00 - 16:00"
打印"可用"
可能有多个这样的案例。 实际上," time2"指的是" Slot已经被其他用户在此期间预订了"" time1"指的是"新用户在此期间请求插槽" P.S:致力于预订系统。
答案 0 :(得分:2)
首先,您解析字符串以查找每个字符串的startTime
和endTime
。
由于这些很简单hour:minute
,您只需将其计算为分钟,即hour * 60 + minute
。
解析开始和结束时间的简单方法是使用正则表达式。
public final class TimeRange {
private final int startMinOfDay;
private final int endMinOfDay;
public TimeRange(String text) {
Pattern p = Pattern.compile("(\\d{1,2}):(\\d{2}) - (\\d{1,2}):(\\d{2})");
Matcher m = p.matcher(text);
if (! m.matches())
throw new IllegalArgumentException("Invalid time range: " + text);
this.startMinOfDay = minOfDay(m.group(1), m.group(2));
this.endMinOfDay = minOfDay(m.group(3), m.group(4));
if (this.endMinOfDay <= this.startMinOfDay)
throw new IllegalArgumentException("Invalid time range: " + text);
}
private static int minOfDay(String hour, String minute) {
int h = Integer.parseInt(hour);
int m = Integer.parseInt(minute);
if (m >= 60 || h >= 24)
throw new IllegalArgumentException("Invalid time: " + hour + ":" + minute);
return h * 60 + m;
}
public boolean overlaps(TimeRange that) {
return (this.startMinOfDay < that.endMinOfDay && this.endMinOfDay > that.startMinOfDay);
}
}
测试
public static void main(String[] args) {
test("14:00 - 16:00", "15:00 - 16:00");
test("14:00 - 17:00", "15:00 - 16:00");
test("15:00 - 16:00", "14:00 - 17:00");
test("14:00 - 15:00", "15:00 - 16:00");
}
private static void test(String time1, String time2) {
System.out.println(new TimeRange(time1).overlaps(new TimeRange(time2)) ? "Not Available" : "Available");
}
输出
Not Available
Not Available
Not Available
Available