Calculate the amount of months between two dates

lakshman nalla
Tera Contributor

hi 

i have a requirement that is we have to two fields one is start date second one is end date, i need to populate the value of the tenure in months please suggest.

1 ACCEPTED SOLUTION

Mohan Mallapu
Kilo Sage
Hi @lakshman nalla ,
Try to use the below script from the glideAjx first to get the difference between dates, Once we got the result from Ajax call, calculate the months from below script.



var startDate = g_form.getValue('statedate');
var endDate = g_form.getValue('enddate');
 
    var ga = new GlideAjax('ScriptInclude');
    ga.addParam('sysparm_name', 'FunctionName');
    ga.addParam('sysparm_date, startDate);
    ga.addParam('sysparm_endDate',endDate ) ;
    ga.getXML(getDuration);



    function getDuration(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        var months = (answer / (1000 * 60 * 60 * 24 * 30));
       alert(months);
    }

View solution in original post

3 REPLIES 3

ersureshbe
Giga Sage
Giga Sage

Hi, Pls use the below code as reference

 (function executeRule(current, previous /*null when async*/) {

    var t = new GlideDateTime(current.from.getDisplayValue());
    var f = new GlideDateTime(current.to.getDisplayValue());

    var duration = GlideDateTime.subtract(t, f).getDayPart();

    var durationYears = Math.floor(duration/365);
    var durationMonths = Math.floor((duration % 365)/30);
    var durationDays = Math.floor((duration % 365)%30);

    current.setValue('year', durationYears);
    current.setValue('month', durationMonths);
    current.setValue('day', durationDays);


})(current, previous);

 

Regards,
Suresh.

Sandeep Rajput
Tera Patron
Tera Patron

@lakshman nalla Use the following script to calculate months between two dates.

 

var dateTimeOne = new GlideDateTime();
dateTimeOne.setDisplayValue('2023-12-12 08:00:20');
var dateTimeTwo = new GlideDateTime();
dateTimeTwo.setDisplayValue('2022-12-12 08:00:20');

var duration = GlideDateTime.subtract(dateTimeTwo,dateTimeOne);
gs.info(Math.round(parseInt(duration.getDurationValue())/30)); 

Hope this helps.

Mohan Mallapu
Kilo Sage
Hi @lakshman nalla ,
Try to use the below script from the glideAjx first to get the difference between dates, Once we got the result from Ajax call, calculate the months from below script.



var startDate = g_form.getValue('statedate');
var endDate = g_form.getValue('enddate');
 
    var ga = new GlideAjax('ScriptInclude');
    ga.addParam('sysparm_name', 'FunctionName');
    ga.addParam('sysparm_date, startDate);
    ga.addParam('sysparm_endDate',endDate ) ;
    ga.getXML(getDuration);



    function getDuration(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        var months = (answer / (1000 * 60 * 60 * 24 * 30));
       alert(months);
    }