Reputation: 5937
I want to get the difference between two DateTime objects as a DateTime and not as a Period or something like that. How can I do that ?
Upvotes: 3
Views: 553
Reputation: 15552
As others have said not sure why you would want this but the following code will give you the number of days between a two dates and if you want it this number plus 1970 date
@Test
public void test() {
DateTime d1 = new DateTime(2011, 1, 1, 0, 0);
DateTime d2 = new DateTime(2011, 2, 1, 0, 0);
int days = Days.daysBetween(d1, d2).getDays();
assertEquals(31, days);
DateTime dateTime = new DateTime(new Date(0), DateTimeZone.UTC).plusDays(days);
assertEquals(new DateTime(1970, 2, 1, 0, 0, 0, DateTimeZone.UTC), dateTime);
}
Upvotes: 0
Reputation: 339
If I understand your question, you can use the calendar class method compareTo for an int value representing the number of milliseconds between the two times.
public int compareTo(Calendar anotherCalendar) Compares the time values (millisecond offsets from the Epoch) represented by two Calendar objects.
Specified by: compareTo in interface Comparable
Parameters: anotherCalendar - the Calendar to be compared.
Returns:
A value of 0 if the time represented by the argument is equal to the time represented by this Calendar;
A value less than 0 if the time of this Calendar is before the time represented by the argument;
A value greater than 0 if the time of this Calendar is after the time represented by the argument.
Throws: NullPointerException - if the specified Calendar is null. IllegalArgumentException - if the time value of the specified Calendar object can't be obtained due to any invalid calendar values.
Upvotes: 0
Reputation: 497
You always can work with DateFormat and Calendar. It will be easy to calculate the difference between two dates.
See DateFormat
, SimpleDateFormat
and Calendar
.
Upvotes: 0
Reputation: 1500075
You can't, because it doesn't make sense.
What's the difference between September 25th 2012 and December 25th 2012? It's two months, or ~60 days (I haven't checked exactly) - but it certainly isn't "February 20th 1970" or anything like that.
If you find yourself wanting the difference as a DateTime
, it means something in your design is messed up, and you should revisit it. If you have trouble working out exactly where the problem is, you can give us more information and we may be able to identify where the types are wrong, but fundamentally what you're asking for won't work.
Upvotes: 4