How to correclty calculate days between two days

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: