Matt Matt - 16 days ago 6
Java Question

Java: Difference between two dates spanning over months

I have the following code that successfully gets me the difference between two days (in days, hours, minutes, seconds):

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date d1 = format.parse(startTime);
Date d2 = format.parse(endTime);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Start: " + startTime);
System.out.println("End: " + endTime);
System.out.println(diffDays + " days, " + diffHours + " hours, " + diffMinutes + " minutes, " + diffSeconds + " seconds");


However, this does not work when the dates cross into another month, for example:

Start: 2013-07-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds

Start: 2013-05-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds


Is it possible to intelligently span over months and get accurate time differences? I am familiar with Joda but would like to stick with standard Java APIs unless this is not possible without something like Joda.

Answer

You are using

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

Should be

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

You'll get the correct result of

Start: 2013-05-31 10:15:01
End: 2013-08-01 11:22:33
62 days, 1 hours, 7 minutes, 32 seconds

Here's the javadoc for the date patterns. dd is day in month. DD is day in year. Your Date objects just weren't parsed the way you expected. Basically the day in year value of 31 was overwriting the month value.

Debuggers are your friend.

Comments