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

@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

Hi Ankur,

 

just a question, how can I get the SYSTEM'S current date and time??

because when I try the following line, as you have in your answer, I don't get the systems now time.

var nowTime = new GlideDateTime();

Hi,

this line should give you system current date/time in GMT

please share your exact script which you are using

Regads
Ankur

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

Rupali1
Tera Contributor

Hello Smith,

 Below script I had tried on my  PDI few time back you can refer this 

 

 

            var sd = g_form.getValue('u_glide_date_2');

            var ed = g_form.getValue('u_glide_date_3');

                        if(sd > ed)

            {//g_form.addErrorMessage("start date should be less than end date.");

           

                        g_form.showFieldMsg('u_glide_date_2',"start date should be less than end date");

            } 

 

 

 

Please mark correct or helpful if it will help you.

 

Thanks,

Rupali Bondar