Link to home
Start Free TrialLog in
Avatar of MehtaJasmin
MehtaJasminFlag for United States of America

asked on

How to calculate the number of days between two Dates?

I'm trying to write a function that will calculate the number of days that exist between two dates,  but have been unable to come up with an adequete solution thus far. In the reasearch that I've done, I've seen some methods convert the dates to milliseconds, subtract, then convert back. In others, they've incrimented a count variable, and simple added days to the earlier date until the two dates matched. Unfortunately, neither of these methods seems completely accurate under all conditions, nor do they seem as elegant as you'd hope them to be.

How have you done this calculation before? Is there a common library or standard function that's commonly used for this calculation?

Thanks in advance.
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

the problem is more in the definition of what you mean by the number of days between two dates. Once that is defined then implementation is generally straight forward. Using a Calendar for the arithmetic is the standard way, and there are also libraries around.

So what is your definition of the number of days between 2 dates?

Avatar of MehtaJasmin

ASKER

My requirement is, if I pass dateA and dateB to the some java method /  API, it should return me how many days they are apart. It should consider if they in the same year/leap year etc. Basically I am coding for password expiry logic where I need to check that last time user has updated password, has it been 60 days yet. If current date is exceeding the 60 day period of validity then I need to prompt user to change the password.

I have dig in to java.util.Calendar API but could not find appropriate method. Also tried writing test program using DateUtils of commons package with getFragmentInDays() and iterator(java.util.Calendar focus,  int rangeStyle). But looks like I need to write quite a bit of math around iterator() to get the result out. So I was looking for any straight api / jar available for my need.

Hope this defines the question better.

Hope this clears the question.
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
For your two Date instances:
final int TIME_OUT_DURATION = 1000 * 60 * 60 * 24 * 60;
boolean needToChangePassword = (d1.getTime() - d2.getTime()) > TIME_OUT_DURATION;

Open in new window

Thanks! Actually had the same idea about the time you posted it. It's a much easier solution to our exact situation than attempting to calculate the time between two arbitrary dates. Thanks again!
thanks mate, let me know if you need any other help.