# To calculate number of months between two dates

By | January 5, 2021

Many times we come across a requirement where you require to calculate the number of months between two Dates. In our blog, we will explain how you can achieve this.

Lets, take an example where we need to calculate the difference of months between two date fields. Here we have created Start Date and Close Date fields against the company entity to find the age of the company in months.

First step is to create 3 new fields against company as displayed in above image.

• Navigate to below path
<<Sage CRM Installation Directory>>\ \<<CRMINSTANCENAME>>\WWWRoot\js\custom
• Create a new js.file and insert the below code
``````var sStartDate = document.getElementById('claus_start_date').value;
var sCloseDate = document.getElementById('claus_close_date').value;
var sDate = sStartDate.substring(0, 2);
var sMonth = sStartDate.substring(3, 5);
sMonth--;
var sMon = sMonth;
var sYear = sStartDate.substring(6, 10);
var sDate1 = sCloseDate.substring(0, 2);
var sMonth1 = sCloseDate.substring(3, 5);
sMonth1--;
var sMon1 = sMonth1;
var sYear1 = sCloseDate.substring(6, 10);
var FormattedStartDate = new Date(sYear, sMon, sDate);
var FormattedCloseDate = new Date(sYear1, sMon1, sDate1);
var Diff = FormattedCloseDate-FormattedStartDate;
var DiffDays = Math.ceil(Diff / (1000 * 60 * 60 * 24));
var DiffMonths = Math.floor(DiffDays / 30);
claus_diff_months.value = DiffMonths;
``````
• Log on to Sage CRM
• Navigate to below path
• Choose the entity and navigate to screen.
• In On change script of Close Date field, add the required function.
Updated Calculation

Once you are done you should find the months calculated for the entered dates. Hope this information helps!