4 Replies Latest reply on Feb 26, 2014 6:20 PM by alvinmac

# Calculating the number of months

Hi guys,

How do I calculate the number of months between two dates

Open Date: 20/02/2014

Close Date: 20/03/2015

Terms in Months: 13

How do I get the year and subtract it and multiply by 12 then add it to the difference of the months? Sorry I'm not well versed in scripting.

• ###### 1. Re: Calculating the number of months

When using JavaScript for date or time calculations one needs to convert the date or time string to a numeric value that ascends or descends in chronological order of the dates or times. One does this converting the date or time character string to the date object. Once the conversion to the date object is done then one can use the properties or methods of the date object to get a vast amount of data.

function Scand(cFormat, cString) {
// convert a date or time string to a date object;
var oDate = util.scand(cFormat, cString);
if(oDate == null) app.alert("Error converting " + cString + " with format of " + cFormat, 0, 0);
return oDate;
}

var cDateFormat = "dd/mm/yyyy"; // format for date string;
// open date values;
var cOpenDate = "20/02/2014";
var oOpenDate = Scand(cDateFormat, cOpenDate);
// close date values;
var cCloseDate = "20/03/2015";
var oCloseDate = Scand(cDateFormat, cCloseDate);
// check that close date is not before the open date;
if(oCloseDate.getTime() < oOpenDate.getTime()){
app.alert("Close date before oepn date!", 0, 0);
} else {
// compute the differences;
var nDiffYears = oCloseDate.getFullYear() - oOpenDate.getFullYear(); // diff in years;

// difference in years * 12 months/year + difference in months;
var nDiffMonths = (nDiffYears * 12) + (oCloseDate.getMonth() - oOpenDate.getMonth());

}
// convert year to months and add to months;
event.value = (nDiffYears * 12) + nDiffMonths;
}

• ###### 2. Re: Calculating the number of months

Hi,

The code is working perfectly. However, my two date fields are editable (field names OpenDate and CloseDate). I noticed in the code, you set a constant values for the two dates?

var cOpenDate = "20/02/2014";

var cCloseDate = "20/03/2015";

How do I set these using my two fields (OpenDate and CloseDate)?

Thanks,

Alvin

• ###### 3. Re: Calculating the number of months

That way you provided the example. You can change the constant string to the code needed to get the value of a field. You might want to add some additional code to prevent using the code until both fields have a non-null value.

• ###### 4. Re: Calculating the number of months

Thanks! It's working fine now.