gpt4 book ai didi

java - 计算两个时隙共有的时间

转载 作者:行者123 更新时间:2023-11-30 07:28:42 25 4
gpt4 key购买 nike

我需要计算两个时隙的共同时间。我想知道是否有一种有效的方法来计算这个。我知道将时间保存在 int 中并不是最好的方法。有人可以建议我一种保存和计算它的新方法吗?

我需要计算两个可用时隙重叠的持续时间。例如,如果我有一个第一个可用时间段是星期四的 10:00 到 13:00,另一个可用时间段是星期四的 12:00 到 14:00,我们可以计算出这两个时间段都可用的时间。

public class TimeSlot implements Cloneable {

int day;
int hourStart;
int hourEnd;
int minutesStart;
int minutesEnd;
int id;

public TimeSlot(int day, int hourStart, int hourEnd, int minutesStart, int minutesEnd) {
this.day = day;
this.hourStart = hourStart;
this.hourEnd = hourEnd;
this.minutesStart = minutesStart;
this.minutesEnd = minutesEnd;
this.id = AutoIDGenerator.getAutoIdTimeSlot();

}

@Override
protected TimeSlot clone() throws CloneNotSupportedException {
return (TimeSlot) super.clone();
}

public boolean isTheSameDay(TimeSlot t) {
if (this.getDay() == t.getDay()) {
return true;
}
return false;
}

/**
*
* @param t
* @return si l'heure fournie est après this timeslot
*/
public boolean isAfter(TimeSlot t) {
if (this.isTheSameDay(t)) {
if (this.getHourEnd() > t.getHourStart()) {
return true;
} else if (this.getHourEnd() == t.getHourStart() && this.getMinutesEnd() > t.getMinutesStart()) {
return true;
}

}
return false;
}

/**
*
* @param t
* @return si l'heure fournie est avant this timeslot
*/
public boolean isBefore(TimeSlot t) {
if (this.isTheSameDay(t)) {
if (this.getHourStart() > t.getHourEnd()) {
return true;
} else if ((this.getHourStart() == t.getHourEnd()) && (this.getMinutesStart() > t.getMinutesEnd())) {
return true;
}
}
return false;
}

public boolean isCompatible(TimeSlot t) {
if (!(isBefore(t)) && !(isAfter(t))) {
return true;
}
return false;

}
}

最佳答案

如果你可以使用joda time,它有一个Interval classan overlap method这正是您所需要的。

第二个最佳解决方案是使用正确的日期表示形式,如果您使用 Java 7 或更早版本,则使用 Date;如果您使用 Java 8,则使用 Instant

使用 Java 8,您的类可能如下所示:

class Timeslot {
Instant start, end;

Duration overlap(Timeslot other) {
long startOverlap = Math.max(this.start.toEpochMilli(), other.start.toEpochMilli());
long endOverlap = Math.min(this.end.toEpochMilli(), other.end.toEpochMilli());
if (endOverlap <= startOverlap) return Duration.ofMillis(0); //or a negative duration?
else return Duration.ofMillis(endOverlap - startOverlap);
}
}

关于java - 计算两个时隙共有的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36459920/

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