Link to home
Start Free TrialLog in
Avatar of Michael Franz
Michael Franz

asked on

Calc the difference in months.

I have the following fields.

basicPolicyInfo_assoc_PolEffDate

basicPolicyInfo_assoc_PolExpDate

I want to find the number of months between the 2
Avatar of Daniel Wilson
Daniel Wilson
Flag of United States of America image

have a look at http://technet.microsoft.com/en-us/library/ms189794.aspx

select datediff(month, asicPolicyInfo_assoc_PolEffDat, basicPolicyInfo_assoc_PolExpDate) from myTable;
Avatar of Michael Franz
Michael Franz

ASKER

sorry, I mispoke the program uses Java. Not sure what to do now.... I did find this....but could not get it to work.

monthDiff = endDate.get(Calendar.MONTH) - startDate.get(Calendar.MONTH);
OK, so it's not a SQL question, but a Java question, and they're not "fields" but variables.  Right?

<Link to StackOverflow removed>
I'd have a look at the joda-time library.

Sorry, I'm no Java expert.
Avatar of Alexandre Simões
Date handling it's simply a mess in JAVA... a huge mess...
You'll fund yourself casting and converting to cast and convert again to get something done.

My advise is to use Joda-Time to deal with dates.

Use the monthsBetween to get it done.
ASKER CERTIFIED SOLUTION
Avatar of dpearson
dpearson

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
Antoher way of doing it in plain java without Joda Time is simply in a loop where you keep adding a month until your date falls after the 2nd date:

int monthDiffs(date date1, Date date2) {
    if (date1.after(date2))
                   throw new IllegalArgumentException("Date2 should be after date1") ;    

    Calendar cal = Calendar.getInstance();
    cal.setTime(date1);
    int nrOfMonths = 0;

    do {
         cal.add(Calendar.MONTH, 1);
         nrOfMonths++;
    } while (cal.getTime().before(date2));

    return nrOfMonths; // or nrOfMonths-1; according to your taste (*)
}

Open in new window


(*) = If the dates are eg. 15-dec-2012 and 1-Jan-2013, do you consider that as a month difference of 1 or 0?
http://technojeeves.com/joomla/index.php/free/71-difference-between-two-dates-in-java

will give you days. You can then compute months (which is somewhat subjective anyway)
thanks for all the help. I finally get to move on to completing the report... Yea!