How can I find the difference between two dates in JDK7, such that the difference can be added back to make the two dates equal?
I tried to use the solution from a similar StackOverflow question, subtracting one date's milliseconds from the other, but this can result in an incorrect difference between dates.
In this example, I try to make a
equal to b
by setting a = (b-a) + a
private void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b, DatatypeFactory datatypeFactory) {
long b_minus_a = b.getTimeInMillis() - a.getTimeInMillis();
Duration delta = datatypeFactory.newDuration(b_minus_a);
delta.addTo(a);
}
But the results are unexpected:
Before
a = "2015-08-29T00:00:00.000Z"
b = "2040-01-01T00:00:00.000Z"
delta = "P24Y4M5DT0H0M0.000S" // 2 days longer than it should be.
After
a = "2040-01-03T00:00:00.000Z"
b = "2040-01-01T00:00:00.000Z"
delta = "P24Y4M5DT0H0M0.000S"
a.equals(b) = false
Joda-Time has this same issue:
private void makeTwoDatesEqual(GregorianCalendar a, GregorianCalendar b) {
DateTime date1 = new DateTime(a);
DateTime date2 = new DateTime(b);
Interval interval = new Interval(a.getTimeInMillis(), b.getTimeInMillis());
Period offsetPeriod = interval.toPeriod();
date1 = date1.plus(offsetPeriod);
date1.equals(date2); // false in my example
}
Before
date1 = "2015-08-29T00:00:00.000-05:00"
date2 = "2040-01-01T00:00:00.000-05:00"
offsetPeriod = "P24Y4M2DT23H"
date1.equals(date2) = false
After
date1 = "2039-12-31T23:00:00.000-05:00"
date2 = "2040-01-01T00:00:00.000-05:00"
offsetPeriod = "P24Y4M2DT23H"
date1.equals(date2) = false
Before it's asked, there should be no need to account for daylight savings or leap years because in each example I'm adding the interval back over the exact same time period from which it was derived.