我正在寻找Java中的库或帮助器类,该类将允许我执行日期间隔的总和和减法。

例如,假设我有以下日期间隔:

A = ["2015-01-01 00:00", "2015-01-20 00:00"]
B = ["2015-01-05 00:00", "2015-01-10 00:00"]
C = ["2015-01-11 00:00", "2015-01-14 00:00"]
D = ["2015-01-19 00:00", "2015-01-25 00:00"]

1                  A               20
|----------------------------------|
    |---------|   |----------|   |------------|
    5    B    10  11    C    14  19    D      25

假设我要计算以下内容:
A - B - C + D = { ["2015-01-01 00:00", "2015-01-05 00:00"[,
                  ]"2015-01-10 00:00", "2015-01-11 00:00"[,
                  ]"2015-01-14 00:00", "2015-01-25 00:00"] }

1   5         10  11         14               25
|---|         |---|          |----------------|

我知道我可以使用纯Java构建自己的逻辑,但是我不想重蹈覆辙。

我正在研究Joda-Time,但是我不知道如何使用它来执行此类操作。

非常感谢!

最佳答案

我正是从Ranges中找到了我需要的东西:guava-libraries

像这样工作:

Range<Date> a = Range.closed(
    new GregorianCalendar(2015, 0, 1).getTime(),
    new GregorianCalendar(2015, 0, 20).getTime());
Range<Date> b = Range.closed(
    new GregorianCalendar(2015, 0, 5).getTime(),
    new GregorianCalendar(2015, 0, 10).getTime());
Range<Date> c = Range.closed(
    new GregorianCalendar(2015, 0, 11).getTime(),
    new GregorianCalendar(2015, 0, 14).getTime());
Range<Date> d = Range.closed(
    new GregorianCalendar(2015, 0, 19).getTime(),
    new GregorianCalendar(2015, 0, 25).getTime());

RangeSet<Date> result = TreeRangeSet.create();
result.add(a);
result.remove(b);
result.remove(c);
result.add(d);

System.out.println(result);

上面的代码打印:
[
    [Thu Jan 01 00:00:00 BRST 2015‥Mon Jan 05 00:00:00 BRST 2015),
    (Sat Jan 10 00:00:00 BRST 2015‥Sun Jan 11 00:00:00 BRST 2015),
    (Wed Jan 14 00:00:00 BRST 2015‥Sun Jan 25 00:00:00 BRST 2015]
]

08-28 17:41