Reputation: 11608
What is the best way to calculate the difference between 01.01.2013 and now so the result looks like 25 days 16 hours 18 minutes 43 seconds?
Upvotes: 1
Views: 3448
Reputation: 157457
String dateStop = "01.01.2013";
long now = System.currentTimeMillis():
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date d1 = null;
Date d2 = null;
try {
d1 = new Date (now);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
long difference = d2.getTime() - d1.getTime();
long differenceBack = difference;
differenceBack = difference / 1000;
int secs = differenceBack % 60;
differenceBack /= 60;
int mins = differenceBack % 60;
differenceBack /= 60;
int hours = differenceBack % 24;
difference is in milliseconds. Then you can simply di some math to calculate days/hours/mins/seconds
Upvotes: 2
Reputation: 25757
Since you have not provided any code, I am not going to just do it for you however that said time can be an interesting topic for a foray of reasons (time zones for a start).
I would suggest this great library http://joda-time.sourceforge.net/
Joda-Time provides a quality replacement for the Java date and time classes. The design allows for multiple calendar systems, while still providing a simple API. The 'default' calendar is the ISO8601 standard which is used by XML. The Gregorian, Julian, Buddhist, Coptic, Ethiopic and Islamic systems are also included, and we welcome further additions. Supporting classes include time zone, duration, format and parsing.
Look at using Periods and something along the lines
DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
// period of 1 year and 7 days
Period period = new Period(start, end);
I used something similar to create a countdown clock, however you fail in your question to state what format (days, seconds, minutes) you want the value returned in. Period however is quite flexible on this front. For example:
// able to calculate whole days between two dates easily
Days days = Days.daysBetween(start, end);
// able to calculate whole months between two dates easily
Months months = Months.monthsBetween(start, end);
Upvotes: 0