我需要计算两个时隙共有的时间。我想知道是否有一个有效的方法来计算这个。我知道在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;
}
}发布于 2016-04-07 06:42:37
如果您可以使用joda time,那么它有一个带有区间类和方法的方法,完全可以满足您的需要。
第二个最佳解决方案是使用适当的日期表示,如果使用Java7或更早,则使用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);
}
}发布于 2016-04-06 19:32:21
最好的方法是使用java.util.Calendar java.util.Calendar类。
您的时隙可以定义为2个日历值的开始和结束时间。您可以使用日历时间的毫秒进行操作(使用方法getTimeInMillis())。
使用java.util.Calendar对时隙,您可以有任何精度的解决方案(日,小时,分钟.)
https://stackoverflow.com/questions/36459920
复制相似问题