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!
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.
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);
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