• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3644
  • Last Modified:

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?
0
supeno
Asked:
supeno
1 Solution
 
cmalakarCommented:
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);

Open in new window

0
 
ksivananthCommented:
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
supenoAuthor 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++;
                  then.add(Calendar.MONTH, 1);
            }
            if (then.get(Calendar.DAY_OF_MONTH) > today.get(Calendar.DAY_OF_MONTH)) {
                     months--;
                  then.add(Calendar.MONTH, -1);
            }
            while (then.get(Calendar.DAY_OF_MONTH) != today.get(Calendar.DAY_OF_MONTH)) {
               days++;
                  then.add(Calendar.DATE, 1);
            }
            while (then.get(Calendar.YEAR) < today.get(Calendar.YEAR)) {
               years++;
                  then.add(Calendar.YEAR, 1);
            }
            return....
0
 
cmalakarCommented:
Was my comment... not useful ..?
0
 
Vee_ModCommented:
Closed, 500 points refunded.
Vee_Mod
Community Support Moderator
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now