6

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

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.

2 Answers 2

15

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);
1
  • The logic is great for calculating Full + Partial months between dates in Apex. I used your logic to get the same in Formula field. Hope some one finds it useful ( (MONTH(EndDate) - MONTH(StartDate)) + IF( (DAY(EndDate) != DAY(StartDate)), ((DAY(EndDate) - DAY(StartDate)) / (DAY(DATE(YEAR(EndDate),MONTH(EndDate)+1,1)-1))), 0 ) ) Commented Feb 23, 2023 at 7:33
2

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;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .