# Months between two dates

In my trigger i would like to calculate the number of months between two date.

For Example if the date format is (DAY/MONTH/YEAR):

START DATE : 07/10/2013

END DATE: 12/01/2014

Number Months=4 because (07/01/2014) plus 1 month for the 5 days

I've tried with many examples, but nothing.

BR

There are a lot of ways you could tackle this. What have you tried to solve this problem so far? How about using the monthsBetween function, and then adding your requirement about a small number of days difference counting as an additional month?

``````Date a = Date.newInstance(2013,10,7);
Date b = Date.newInstance(2014,1,12);
Integer monthDiff = a.monthsBetween(b);
if (b.day() > a.day()) monthDiff++;
System.debug(monthDiff);
``````

My requirement was to calculate the absolute difference like 5.5 months instead only 5. Posting here may help someone.

`````` Integer monthDiff = a.AgreementStartDate__c.monthsBetween(a.AgreementEndDate__c);
Integer daysEnd = Date.daysInMonth(a.AgreementEndDate__c.year(), a.AgreementEndDate__c.month());
Decimal day_s = a.AgreementStartDate__c.day();
Decimal day_e = a.AgreementEndDate__c.day();
Decimal factor = 0;
if(day_s != day_e){
factor = (day_e - day_s)/daysEnd;
}
a.AgreementTerm__c = monthDiff+factor;
``````