How to correclty calculate days between two days

April 13, 2009

The standard Java API has no solution to calculate the period between two days, although this is a common request for someone who is doing calendar arithmetic.

Googling around, the are many people who expose their own solutions (see some of them 1, 2, 3, 4).  All them suggest getting difference between the two dates, measured in number of milliseconds, and divide by 1000 * 60 * 60 * 24 (that means, the number of milliseconds in a day typical day).

However, are these results really reliable? I think not. All those that I have read did not yet consider correctly both daylight savings time changes and leap years.

And looking at the forums, I found many people arguing about their solutions, nevertheless, I suspect that all them are wrong.

Fortunately, one may resort on Joda Time,  small and reliable Java package that replaces the Java date and time API and provides tools for all calendar arithmetic. I really recommend getting to know with this package.

Calculating the number of days between two days becomes as simple as (see more):

  Days d = Days.daysBetween(startDate, endDate);
  int days = d.getDays();

And all calendar details and pitfalls are correctly handled by Joda Time. Much metter than relaying on self-, handmade solutions that one cannot easily guarantee to be correct for all situations.

Entry Filed under: Java. .

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Disclaimer

This is the technical weblog of Daniel Felix Ferber. The postings on this site are his own and don’t necessarily represent neither IBM’s, Stefanini IT Solutions nor Petrobras positions, strategies or opinions.

My Personal Weblog

This weblog is dedicated for my technical articles written in English. If you are interested in my personal thoughs, or my articles in Portuguese, please visit Daniel Ferbers Weblog.

Blogroll

Feeds

Pages

 

April 2009
M T W T F S S
« Mar   Aug »
 12345
6789101112
13141516171819
20212223242526
27282930  

Archives

Meta