This question already has an answer here:
I want to calculate difference between 2 dates in hours/minutes/seconds.
I have a slight problem with my code here it is :
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 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.");
This should produce :
Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
However I get this result :
Time in seconds: 225 seconds.
Time in minutes: 3 minutes.
Time in hours: 0 hours.
Can anyone see what I'm doing wrong here ?
Here is my code.
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 ;-)
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.difference-between-two-dates-in-java
Extracted the code from the link
If you are able to use external libraries I would recommend you to use Joda-Time, noting that:
Example for between calculation:
Create a
Date
object using the diffence between your times as a constructor,then use Calendar methods to get values ..