How to compare two dates (i.e., GlideDateTimes) within a script?

Smith Johnson
Tera Guru

Hello there,

I would like to know how I could compare two dates within a script.

I have the following snippet:

var grGr=new GlideRecord("u_orders");

grGr.query();

var date;
var today = new GlideDateTime();  //get the current date

while(grGr.next()){
   date=grGr.getValue("u_created");
   date = new GlideDateTime(date);  //get the date that the order was created

   gs.info(today);
   gs.info(date);

   //HERE I WANT TO COMPARE THE TWO DATES
}



In the following image, you can see the result of one iteration.

find_real_file.png

 

How can I compare the first date (today's date) with the second date (the date that an order created) and see if today's date is greater than the order's date?

 

Thank you,

Smith.

1 ACCEPTED SOLUTION

@Smith Johnson 

Example below

Script I ran and the output:

var dateField = new GlideDateTime('2021-05-04');

var nowTime = new GlideDateTime();

var dur = new GlideDuration();

dur = GlideDateTime.subtract(dateField, nowTime);

var days = dur.getDayPart();

gs.info(days);

Output:

[0:00:00.066] Script completed in scope global: script


Script execution history and recovery available here


*** Script: 2

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

8 REPLIES 8

Deepshikha 3010
Mega Guru

Hii Smith,

please refer this link

https://docs.servicenow.com/bundle/london-application-development/page/script/business-rules/concept/c_ComparingTwoDateFields.html

Regards

Deepshikha Pandey

Dan Ellis
Kilo Sage

You need to get the milliseconds of the 2 dates and then you can compare then like a normal number.

var grGr = new GlideRecord("u_order");
grGr.query();

var date;
var today = new GlideDateTime(); //get the current date

while(grGr.next()) {
    date = grGr.getValue("u_created");
    date = new GlideDateTime(date); //get the date that the order was created

    if (today.getNumericValue() > date.getNumericValue()) {
        gs.info("Order was created before today");
    }
    else {
        gs.info("Order was NOT created before today");
    }

}

Prasad Dhumal
Mega Sage
Mega Sage

Hello Author,

You can convert the two date fields into milliseconds by using

today.getNumericValue() and date.getNumericValue()

and then compare today with date to get appropriate output.    

Please mark Correct✅/helpful if applicable, thanks!!

Prasad

 

Ankur Bawiskar
Tera Patron
Tera Patron

@Smith Johnson 

you want to get the difference between 2 date/times so you can use OOB GlideDateTime.subtract() method

subtract(GlideDateTime start, GlideDateTime end)

you can get the difference in terms of Hours Days Minutes or only days etc

please refer the docs link and check the required functions

Regards
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader