+ Start a Discussion
Marilyne PMarilyne P 

Apex code to calculate number of months between two dates

Hello,

How can i calculat number of months between two dates, in apex ?

Thank you for advice
Best Answer chosen by Marilyne P
RKSalesforceRKSalesforce
Hi Marilyne,

Please use below formula:
IF(
(testdate2__c - testdate1__c) / 365 * 12 < 1, 1, (testdate2__c - testdate1__c) / 365 * 12
)

OR Below Apex code :
If((testdate2__c - testdate1__c) / 365 * 12 < 1){
	month = 1;
} else {
	month = (testdate2__c - testdate1__c) / 365 * 12;
}

Hope this will work. Please mark as best answer if helped.

Regards,
Ramakant

All Answers

RKSalesforceRKSalesforce
Hi Marilyne,

Please use below formula:
IF(
(testdate2__c - testdate1__c) / 365 * 12 < 1, 1, (testdate2__c - testdate1__c) / 365 * 12
)

OR Below Apex code :
If((testdate2__c - testdate1__c) / 365 * 12 < 1){
	month = 1;
} else {
	month = (testdate2__c - testdate1__c) / 365 * 12;
}

Hope this will work. Please mark as best answer if helped.

Regards,
Ramakant
This was selected as the best answer
Vinod ChoudharyVinod Choudhary
Hi Marilyne,

There are a lot of ways you could tackle this.
 
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);
OR
 
IF( 
(testdate2__c - testdate1__c) / 365 * 12 < 1, 1, (testdate2__c - testdate1__c) / 365 * 12
)

Thanks
Vinod
 
Waqar Hussain SFWaqar Hussain SF
//count from 1st day of start date
Date a = Date.newInstance(2017,10,7).toStartOfMonth();
//calculating total number of days in end date
Integer TotalDaysInLastMonth = Date.daysInMonth(Date.newInstance(2018,1,12));
Integer monthDiff = a.monthsBetween(Date.newInstance(2018,1,TotalDaysInLastMonth));
System.debug(monthDiff);