I know this is an old question, but I ended up doing something slightly different from the accepted answer. People talk about the TimeUnit
class, but there were no answers using this in the way OP wanted it.
So here's another solution, should someone come by missing it ;-)
public class DateTesting {
public static void main(String[] args) {
String dateStart = "11/03/14 09:29:58";
String dateStop = "11/03/14 09:33:43";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long days = TimeUnit.MILLISECONDS.toDays(diff);
long remainingHoursInMillis = diff - TimeUnit.DAYS.toMillis(days);
long hours = TimeUnit.MILLISECONDS.toHours(remainingHoursInMillis);
long remainingMinutesInMillis = remainingHoursInMillis - TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(remainingMinutesInMillis);
long remainingSecondsInMillis = remainingMinutesInMillis - TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(remainingSecondsInMillis);
System.out.println("Days: " + days + ", hours: " + hours + ", minutes: " + minutes + ", seconds: " + seconds);
}
}
Although just calculating the difference yourself can be done, it's not very meaningful to do it like that and I think TimeUnit
is a highly overlooked class.