我有两个 DateTime
间隔列表,我想获得这些列表的析取。有谁知道怎么计算吗?
每个间隔都保存为一个对象:
public class Interval {
LocalDateTime start;
LocalDateTime end;
}
例如我有:
List<Interval> list1 >> [from 10:00 to 12:00] and [from 13:00 to 14:00]
List<Interval> list2 >> [from 10:00 to 11:00] and [from 13:30 to 14:00]
我想要得到的结果是它们不重叠的间隔:
List<Interval> result >> [from 11:00 to 12:00] and [from 13:00 to 13:30]
最佳答案
您可以手动完成所有操作,也可以使用我的库 Time4J并研究这个例子,接受你的输入,产生预期的输出。据我正确理解,您正在寻找 minus-operation ,即从一个间隔列表中减去另一个间隔列表:
// first collect the intervals from "list1" into an IntervalCollection
TimestampInterval i1 =
TimestampInterval.between(
LocalDateTime.of(2017, 9, 9, 10, 0),
LocalDateTime.of(2017, 9, 9, 12, 0));
TimestampInterval i2 =
TimestampInterval.between(
LocalDateTime.of(2017, 9, 9, 13, 0),
LocalDateTime.of(2017, 9, 9, 14, 0));
IntervalCollection<PlainTimestamp> ic =
IntervalCollection.onTimestampAxis().plus(Arrays.asList(i1, i2));
// then collect the intervals from "list2" as simple interval list
TimestampInterval j1 =
TimestampInterval.between(
LocalDateTime.of(2017, 9, 9, 10, 0),
LocalDateTime.of(2017, 9, 9, 11, 0));
TimestampInterval j2 =
TimestampInterval.between(
LocalDateTime.of(2017, 9, 9, 13, 30),
LocalDateTime.of(2017, 9, 9, 14, 0));
// finally perform the minus-operation
List<ChronoInterval<PlainTimestamp>> result = ic.minus(Arrays.asList(j1, j2)).getIntervals();
System.out.println(result);
// output: [[2017-09-09T11/2017-09-09T12), [2017-09-09T13/2017-09-09T13:30)]
// Alternative to get back `LocalDateTime`-objects for start (inclusive) and end (exclusive):
for (ChronoInterval<PlainTimestamp> interval : result) {
LocalDateTime start = interval.getStart().getTemporal().toTemporalAccessor();
LocalDateTime end = interval.getEnd().getTemporal().toTemporalAccessor();
System.out.println(start + "/" + end);
}
关于java - 如何使用 java 8 从日期时间间隔中获取析取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46122615/