Time date comparision

servicenow14710
Tera Expert

Hello developers, please check this code as it is not working when imm trying to compare two dates  . If condition is satisfying in every scenario even when condition is not matched as per the scenario. 

var date = '2024-06-01';

var gd = new GlideDate();

gd.setValue(date);

gs.print('newValue = ' + gd + ' & getdisplayvalue = ' + gd.getDisplayValue(), 'PF');

 

var today = new GlideDate();

gs.print("today:" + today.getDisplayValue());

 

var format = new GlideDate();

format.addMonths(-4);

gs.print('format = ' + format.getDisplayValue());

 

if (gd.getDisplayValue()<format.getDisplayValue()) {

    gs.print('***************ERROR**************'+gd.getDisplayValue() + ' < ' + format.getDisplayValue(), 'PF');

    check = true;

}

gs.print('check = ' + check);

Thanks!

1 REPLY 1

Zach Koch
Giga Sage
Giga Sage

Your script has a couple different errors. If you want a specific date to be a GlideDateTime object, you can use it as argument for GlideDateTime('2024-06-01') or GlideDateTIme(yourVariable).  You then can use the date1.compareTo(date2) to compare the dates. The script below should help you accomplish the comparison, and a screenshot of the docs page for this method is also included, as well as the link.

 

 

var date = new GlideDateTime('2024-06-01');
var today = new GlideDate();
var check = false;

today.addMonths(-4);
if (today.compareTo(date) == -1 || today.compareTo(date) == 0) {
    check = true;
}

gs.print('check = ' + check);

 

 

 

ZachKoch_0-1722431713539.png

Docs for compare 

 

If this information helped resolve your issue, please remember to mark response correct and thumbs up to help future community members on this information, thanks!