gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:52:15 27 4
gpt4 key购买 nike

我有两个 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/

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