Java: Difference between two dates spanning over months -


i have following code gets me difference between 2 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, not work when dates cross month, 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 possible intelligently span on months , accurate time differences? familiar joda stick standard java apis unless not possible without joda.

you 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 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 javadoc date patterns. dd day in month. dd day in year. date objects weren't parsed way expected. day in year value of 31 overwriting month value.

debuggers friend.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -