gpt4 book ai didi

java - 比较 Java 中的日期时间 DAY hh :mm-hh:mm

转载 作者:行者123 更新时间:2023-12-02 11:54:50 24 4
gpt4 key购买 nike

我们如何在java中比较日期并获取剩余的可用插槽?

Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00

那么除了这三个时段之外,我们如何才能获得一天中的所有可用时间呢?我们如何在java中比较这些日期?有人可以建议一下吗?

最佳答案

为占用的槽位设计一个类。听起来您需要一个 DayOfWeek 字段和两个 LocalTime 字段。将日期时间解析为这样的对象:在连字符处分割并使用几个 DateTimeFormatter。对你的物体进行排序。对于每对相邻对象,确定它们之间是否有空槽(如果存在重叠,也会报告错误)。您还需要决定是否考虑在第一个日期时间之前(周日 00:00 到 10:00?)和最后一个日期之后有空位。

我故意提到现代 Java 日期和时间 API java.time 中的类和 enum。合作起来很愉快,我毫不犹豫地推荐它。

编辑:您现在有五天的时间来编写类(class)代码,因此可能是时候分享我的版本,以便您进行比较并供 future 的读者使用。

public class Slot {

private static Pattern textPattern = Pattern.compile("(\\w+) ([0-9:]+)-([0-9:]+)");
private static DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("EEE");

public static Slot parse(String text) {
Matcher textMatcher = textPattern.matcher(text);
if (textMatcher.matches()) {
DayOfWeek day = DayOfWeek.from(dayFormatter.parse(textMatcher.group(1)));
LocalTime startTime = LocalTime.parse(textMatcher.group(2));
LocalTime endTime = LocalTime.parse(textMatcher.group(3));
return new Slot(day, startTime, endTime);
} else {
throw new IllegalArgumentException("Unparsable slot " + text + ", expected format Sun 12:00-14:00");
}
}

private final DayOfWeek day;
private final LocalTime startTime;
private final LocalTime endTime;

Slot(DayOfWeek day, LocalTime startTime, LocalTime endTime) {
if (! endTime.isAfter(startTime)) {
throw new IllegalArgumentException("End time must be after start time");
}
this.day = Objects.requireNonNull(day);
this.startTime = startTime;
this.endTime = endTime;
}

public DayOfWeek getDay() {
return day;
}

public LocalTime getStartTime() {
return startTime;
}

public LocalTime getEndTime() {
return endTime;
}

/**
* @param nextSlot
* @return A new Slot object representing the vacant Slot between this Slot and nextSlot,
* or an empty Optional if no gap
*/
public Optional<Slot> slotBetween(Slot nextSlot) {
if (! nextSlot.getDay().equals(day)) {
throw new IllegalArgumentException("Cannot compare slots on different days of week");
}
if (nextSlot.getStartTime().isBefore(endTime)) {
throw new IllegalArgumentException("Error: overlap between slots " + this + " and " + nextSlot);
}
if (nextSlot.getStartTime().isAfter(endTime)) { // there is a gap
return Optional.of(new Slot(day, endTime, nextSlot.getStartTime()));
} else {
return Optional.empty();
}
}

@Override
public String toString() {
return dayFormatter.format(day) + ' ' + startTime + '-' + endTime;
}

}

关于java - 比较 Java 中的日期时间 DAY hh :mm-hh:mm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47667338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com