views:

48

answers:

2

I'm sure this has been asked before in some other way that I just can't find, so I apologize upfront for repeating if I am.

I am trying to calculate the difference between two dates and then display that difference in days, minutes, and seconds; something like "3 days 23 minutes and 59 seconds"

Very easy, I'm sure, but I'm a C# guy by practice so I'm having a hard time thinking out of the box on this one.

Thanks in advance!

+2  A: 
Date start = new Date(2010, 10, 13);
Date end   = new Date(2010, 10, 18);

long diffInMillis = end.getTime() - start.getTime();

long diffInDays  = diffInMillis/1000/86400;
long diffInHours = (diffInMillis/1000 - 86400*diffInDays) / 3600;
long diffInMins  = (diffInMillis/1000 - 86400*diffInDays - 3600*diffInHours) / 60;
long diffInSecs  = (diffInMillis/1000 - 86400*diffInDays - 3600*diffInHours - 60*diffInMins);
Mark E
Somethin's wrong with the numbers used. This is the direction I would like to go though.
BennyT
@BennyT, should work now.
Mark E
Thank you, @Mark!
BennyT
+3  A: 

There is no direct to do this with the Calendar and Date objects that are currently part of the standard Java API. You could find the number of milliseconds between the two dates and use arithmetic. This depends on your accuracy needs such as if you need to account for leap years. That would make the calculation more messy, but still doable.

The Joda-Time library offers a Period object that does exactly what you are looking to do.

laz
I would stick to Joda for now, the built-in Calendar stuff is enough to make you nauseous.
Joe
I would but including a lib for one tiny part of my app doesn't make much sense, does it?
BennyT