I didn't find anything in the Android SDK which does a similar job (Google included one in the GWT framework...maybe one could take it out there).
But since it is not too difficult I wrote a DateUtils class myself which does a similar job. I like the friendly date formats which are also used in Gmail like "Yesterday" or "2 min ago" rather than a date like 13/08/2010 or 10:30 PM.
To what regards time differences I wrote the following
public static String getDifference(Date sessionStart, Date sessionEnd) {
if(sessionStart == null)
return "[corrupted]";
Calendar startDateTime = Calendar.getInstance();
startDateTime.setTime(sessionStart);
Calendar endDateTime = Calendar.getInstance();
endDateTime.setTime(sessionEnd);
long milliseconds1 = startDateTime.getTimeInMillis();
long milliseconds2 = endDateTime.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long hours = diff / (60 * 60 * 1000);
long minutes = diff / (60 * 1000);
minutes = minutes - 60 * hours;
long seconds = diff / (1000);
if (hours > 0) {
return hours + " hours " + minutes + " minutes";
} else {
if (minutes > 0)
return minutes + " minutes";
else {
return seconds + " seconds";
}
}
}
..and here is the according unit test to verify the correct functioning:
@Test
public void testGetDifference() {
// hours and minutes
Date startDate = DateUtils.createDateInstance("01.01.2010 12:00:00");
Date endDate = DateUtils.createDateInstance("01.01.2010 13:12:00");
String difference = DateUtils.getDifference(startDate, endDate);
assertNotNull(difference);
assertEquals("1 hours 12 minutes", difference);
// minutes
startDate = DateUtils.createDateInstance("01.01.2010 12:00:00");
endDate = DateUtils.createDateInstance("01.01.2010 12:02:00");
difference = DateUtils.getDifference(startDate, endDate);
assertNotNull(difference);
assertEquals("2 minutes", difference);
// seconds
startDate = DateUtils.createDateInstance("01.01.2010 12:00:00");
endDate = DateUtils.createDateInstance("01.01.2010 12:00:15");
difference = DateUtils.getDifference(startDate, endDate);
assertNotNull(difference);
assertEquals("15 seconds", difference);
difference = DateUtils.getDifference(null, endDate);
assertEquals("[corrupted]", difference);
}
You may have to tune it a bit and also externalize the hardcoded strings ("hours", "minutes",...) in order to make everything easier to localize (if that's an issue for you).
Just as a reference, it may probably also be worth looking at the JodaTime lib. Maybe they have a similar implementation, but I didn't verify that myself (yet).