I am trying to compute the difference in time between two date/times. This is what I have imported:
import java.util.concurrent.TimeUnit;
import java.text.*;
import java.util.*;
And this is my code:
SimpleDateFormat format= new SimpleDateFormat("yy/MM/dd HH:mm:ss");
String dateStart = "11/03/14 19:29:58";
String dateStop = "11/05/14 08:03:13";
Date d1=null;
Date d2=null;
try{
d1 = format.parse(dateStart);
d2=format.parse(dateStop);
}
catch(ParseException e)
{
e.printStackTrace();
}
long diff = d2.getTime()-d1.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes=TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println(minutes);
This, I think, should work fine, but instead of the correct answer I get "87153". What is the source of error and how can I correct it?
That looks correct to me... you've got just under two months, so 60.5 days (because it starts at ~8pm and ends at ~8am). A day contains 1440 minutes. 1440 * 60.5 is 87120, which is very close to the answer you've received.
It's not clear what answer you expected, but Java's getting the maths right. The source of the error is presumably your expectations :)
(As an aside, you may well want to specify a time zone of UTC unless you want calculations like this to use your local time zone. You could easily get answers which are an hour off your expected results for that reason.)
See more on this question at Stackoverflow