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!
DATE field can be used to add or subtract dates in Java. Positive value passed into add() method will add days into date while negative values will subtract days from date in Java. Similarly Calendar. MONTH can be used to add and subtract months from date in Java.
The minusDays() method of LocalDate class in Java is used to subtract the number of specified day from this LocalDate and return a copy of LocalDate. For example, 2019-01-01 minus one day would result in 2018-12-31.
getTime() + d2. getTime(); Date sumDate = new Date(sum); The code uses the . getTime() method that returns the number of milliseconds since the epoch.
DateTime yesterday = new DateTime(). minusDays(1);
I found exactly what I needed: Ranges, from the guava-libraries.
Works like this:
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);
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]
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With