 ShowAll Questionssorted byDate Posted Marilyne P

# Apex code to calculate number of months between two dates

Hello,

How can i calculat number of months between two dates, in apex ? Best Answer chosen by Marilyne P RKSalesforce
Hi Marilyne,

```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;
}```

Regards,
Ramakant RKSalesforce
Hi Marilyne,

```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;
}```

Regards,
Ramakant
This was selected as the best answer Vinod 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 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);```