Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Difference between two dates spanning over months

Tags:

java

date

time

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.

like image 666
Matt Avatar asked Dec 15 '22 07:12

Matt


1 Answers

While you should use Joda Time simply as a much better date/time API, I suspect the problem is actually just that you're parsing the values incorrectly. Use a format string of:

yyyy-MM-dd HH:mm:ss

... with dd instead of DD. The DD value is "day in year" which I suspect is confusing things, basically overriding the month part entirely. See the SimpleDateFormat documentation for more details.

You can validate what's wrong by printing out d1 and d2 after parsing...

like image 119
Jon Skeet Avatar answered Dec 30 '22 23:12

Jon Skeet