简体   繁体   English

如何使用Java 8从日期时间间隔中分离

[英]How to get disjunction from datetime intervals using java 8

I have two DateTime interval lists and I want to get the disjunction of these ones. 我有两个DateTime间隔列表,但我想将它们分开。 Does anyone know how could it be calculated? 有谁知道如何计算?

Each interval is saved as an object: 每个间隔都保存为一个对象:

public class Interval {
    LocalDateTime start;
    LocalDateTime end;
}

For example I have: 例如,我有:

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]

The result that I want to get is the intervals where they don't overlap: 我想要得到的结果是它们不重叠的间隔:

List<Interval> result >> [from 11:00 to 12:00] and [from 13:00 to 13:30]

Either you can do it all manually, or you can use my library Time4J and study this example taking your input which yields the expected output. 您既可以手动完成所有操作,也可以使用我的库Time4J并研究此示例以获取可产生预期输出的输入。 As far as I have understood you correctly, you are looking for a minus-operation , ie subtracting one list of intervals from another one: 据我正确理解,您正在寻找减号运算符 ,即从另一个列表中减去一个间隔列表:

// 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM