I have a code which calculates the difference between two dates in terms of hours/minutes/seconds. But when I am executing the below code, it is not giving me the accurate difference in seconds. Can someone suggest, where my code is going wrong?
String startDate = "11/03/14 09:29:58";
String stopDate = "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(startDate);
d2 = format.parse(stopDate);
} catch (ParseException e) {
e.printStackTrace();
}
// Get msec from each, and subtract.
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Time in seconds: " + diffSeconds + " seconds.");
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
My output is:
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
But the correct output should be:
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Please help.