# subtract two dates to find months between them

I know this has come up before but I haven't found a clean solution.
I want to subtract an old date from today to find out how old something is in months. It's to do with insurance valuations.
I have a solution using arithmatic which doesn't always get it right , as in adding a day extra occasionally.
It's all a bit messy. Is there a nice neat, clean solution using Calendar or something?
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Is this what you want...

`````` Calendar cal = Calendar.getInstance();
Calendar old = Calendar.getInstance();
old.set(2007, 0, 8);
int years = cal.get(Calendar.YEAR) - old.get(Calendar.YEAR);
int extraDays = cal.get(Calendar.DAY_OF_MONTH) + 1 + old.getActualMaximum(Calendar.DAY_OF_MONTH) - old.get(Calendar.DAY_OF_MONTH);
int months = (years - 1) * 12 + ( cal.get(Calendar.MONTH)) + (11 - old.get(Calendar.MONTH)) + (extraDays/30);

System.out.println("Months: " + months);
``````
0
Commented:
0
Commented:
0
Author Commented:
I found this searching web:
int years = 0;
int months = 0;
int days = 0;
Date now = new java.util.Date();
Calendar today = Calendar.getInstance();
today.setTime(now);

Calendar then = Calendar.getInstance();
then.setTime(dateBought);
while (then.get(Calendar.MONTH) != today.get(Calendar.MONTH)) {
months++;
}
if (then.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH)) {
months--;
}
while (then.get(Calendar.DAY_OF_MONTH) != today.get(Calendar.DAY_OF_MONTH)) {
days++;
}
while (then.get(Calendar.YEAR) < today.get(Calendar.YEAR)) {
years++;
}
return....
0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
Was my comment... not useful ..?
0
Commented:
Closed, 500 points refunded.
Vee_Mod
Community Support Moderator
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.