java两个时间加减法,Java中的日期间隔加减法

I'm looking for a library or helper class in Java that would allow me to perform date interval sum and subtractions.

For example, lets's say I have the following date intervals:

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

And let's say I'd like to calculate the following:

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

|---| |---| |----------------|

I know I can build my own logic using pure Java, but I'd rather not reinvent the wheel...

I was looking into Joda-Time, but I couldn't figure out how to perform such operations using it.

Thanks a lot!

解决方案

I found exactly what I needed: Ranges, from the guava-libraries.

Works like this:

Range a = Range.closed(

new GregorianCalendar(2015, 0, 1).getTime(),

new GregorianCalendar(2015, 0, 20).getTime());

Range b = Range.closed(

new GregorianCalendar(2015, 0, 5).getTime(),

new GregorianCalendar(2015, 0, 10).getTime());

Range c = Range.closed(

new GregorianCalendar(2015, 0, 11).getTime(),

new GregorianCalendar(2015, 0, 14).getTime());

Range d = Range.closed(

new GregorianCalendar(2015, 0, 19).getTime(),

new GregorianCalendar(2015, 0, 25).getTime());

RangeSet result = TreeRangeSet.create();

result.add(a);

result.remove(b);

result.remove(c);

result.add(d);

System.out.println(result);

The code above prints:

[

[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]

]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值