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 ?
long diffSeconds = (diff / 1000)%60;
try this and let me know if it works correctly...
This is more of a maths problem than a java problem basically.
The result you receive is correct. This because 225 seconds is 3 minutes (when doing an integral division). What you want is the this:
or in java:
I would prefer to use suggested
java.util.concurrent.TimeUnit
class.Try this for a friendly representation of time differences (in milliseconds):
Joda-Time
Joda-Time 2.3 library offers already-debugged code for this chore.
Joad-Time includes three classes to represent a span of time:
Period
,Interval
, andDuration
.Period
tracks a span as a number of months, days, hours, etc. (not tied to the timeline).When run…
Well, I'll try yet another code sample: