How to calculate difference between two dates and show it on DAYS?

reinaldo_vieira
Tera Contributor

Hello!

I'm working on a challenge that asks me to calculate the date difference in 2 fields of a Service Portal form and impose form blocks and error-type messages depending on the result.

 

Calculating difference between two dates - Service Catalog form.jpeg

The two fields in the form are of type Date (not Date/Time).

Can this be done directly via Client Script or is it better to use a combination of Script Include GlideAJAX Script + Catalog Client Script onChange?

IMPORTANT:
- The date in "data_inicio_emprestimo" CANNOT be less than the current date. If it is, the field will display an error message and the form cannot be submitted.

- The date difference between the fields (data_inicio_emprestimo / data_final_emprestimo) must be a maximum of 7 days. If the difference is greater than 7 days, the field will display an error text message and the form cannot be submitted.

8 REPLIES 8

HII @reinaldo_vieira 

I have worked this script based on your requirement,here is the script and code

Scriptinclude:

var Diff_date = Class.create();
Diff_date.prototype = Object.extendsObject(AbstractAjaxProcessor, {

  calculatedate: function() {
 
              var startDate = new GlideDate();


              startDate.setDisplayValue(this.getParameter('sysparm_start'));


              var endDate = new GlideDate();


              endDate.setDisplayValue(this.getParameter('sysparm_end'));


              var duration = new GlideDuration();


              duration= GlideDate.subtract(startDate, endDate);


              return duration.getDayPart();  
    },

    type: 'Diff_date'
});
 
ClientScript:
function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
var startDate = g_form.getValue('start_date');
var endDate = newValue;
var maxDays = 7;
//maxDays.setDisplayValue(7);
alert(maxDays);
alert(startDate);
alert(endDate);

var ga = new GlideAjax('global.Diff_date');
ga.addParam('sysparm_name', 'calculatedate');
ga.addParam('sysparm_start', startDate);
ga.addParam('sysparm_end', endDate);
ga.getXML(callback);

function callback(response) {
var answer = response.responseXML.documentElement.getAttribute('answer');
alert(answer);
if (answer > maxDays) {
    alert('test');
g_form.showFieldMsg('end_date', 'Você ultrapassou o limite de 7 dias. Por favor, escolha um período mais curto', 'error');
} else {
alert('Deu errado...'); //to check if Script Include and Client Script are running ok
}

}

}
   Screenshots:
SHARANsnow7_0-1697116313852.pngSHARANsnow7_1-1697116338887.pngSHARANsnow7_2-1697116381859.png

Mark my answer helpful & accepted if it helps you resolve your query.


Regards
Sharan

Hello, @SHARANsnow7 

 

I tried getXML but unfortunately it didn't work. From what I read later in this article, I think getXMLAnswer was a better fit for my attempt.

 

I'll share the code that worked for me.

 

Thanks,

 

Reinaldo Vieira

 

SCRIPT INCLUDE
 

 

var DifferDates = Class.create();
DifferDates.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    calcularDias: function() {
        var from = new GlideDate();
        from.setDisplayValue(this._transformDate(this.getParameter('sysparm_start'))); //define um valor de data usando o formato de exibição e o fuso horário do usuário atual

        var to = new GlideDate();
        to.setDisplayValue(this._transformDate(this.getParameter('sysparm_end')));

        var difference = GlideDate.subtract(from, to);
        var days = difference.getDayPart(); //retorna o número de dias

        return days;

    },

    _transformDate: function(date) {
        date = date.split('/');
        return date = date[2] + '-' + date[1] + '-' + date[0];
    },

    type: 'DifferDates'
});

 

 
CLIENT SCRIPT
 

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    //Type appropriate comment here, and begin script below
    var startDate = g_form.getValue('data_inicio_emprestimo');
    var endDate = g_form.getValue('data_final_emprestimo');
    var maxDays = 7;

    var ga = new GlideAjax('global.DifferDates');
    ga.addParam('sysparm_name', 'calcularDias');
    ga.addParam('sysparm_start', startDate);
    ga.addParam('sysparm_end', endDate);
    ga.getXMLAnswer(callback);

    function callback(response) {
        if (response > maxDays) {
            g_form.showFieldMsg('data_final_emprestimo', 'Você ultrapassou o limite de 7 dias. Por favor, escolha um período mais curto.', 'error');
        } else {
            alert('Deu errado...'); //to check if Script Include and Client Script are running ok
        }

    }

}

 

Hello, @Jagadish Sanadi 

 

I've tested up here with some other conversations on the subject and I like this solution. I would also add an internal function to the Include script to transform the date - in the GlideDate documentation, the expected format for the subtract is yyyy-MM-dd.

 

Best regards,

 

Reinaldo Vieira

function callback(response) {
var answer = response.responsexml.documentelement.getattribute( answer );

if(answer>maxDays)

{
g_form.showFieldMsg('data_final_emprestimo', 'Você ultrapassou o limite de 7 dias. Por favor, escolha um período mais curto.', 'error');

}

}

 

Please check this and mark useful if this helped you