To compare two dates and set a business rule based on which is earlier

ahammoud
Tera Guru

I have an item created in the Service Catalog called "Order Business Cards".
I set up a bunch of variables in it, one of them is called "Delivery Date" (delivery_date) that is specified by the user.
I want to compare the 'delivery_date' specified by the user with the actual current date and then alert them if the 'delivery_date' is within 7 days from current date (less than a week from today). I set up a Business Rule on the Requested Item table (sc_req_item) set to 'before' insert.
What I did, is created 2 variables one equal to the value set by the user and the other to current date + 7 days. I verified that the variables are containing the correct value, but I am trying to use the compare Dates methods, to generate the message, but it doesn't work:


var date = current.variables.delivery_date;
var date2 = new GlideDate(); //set date2 = today's date
date2.addDays(+7); // adds 7 days to date2

gs.addInfoMessage(date); //displays on page the correct date
gs.addInfoMessage(date2); //displays on page the correct date

var test = gs.print(date.compareTo(date2));
if ( test == '-1'){
gs.addInfoMessage('Please allow 7 days for delivery');
}



Note: this is where compare dates method is found:
https://wiki.servicenow.com/index.php?title=GlideDateTime#compareTo.28o.29

8 REPLIES 8

shabaab_mazhar
Mega Expert

You can refer to the forum how the dates are compared on Client Side

Client Script Date/Time Functions

Let me know if that doesn't work.


The WIKI states to use 'Date/Time' object; does compareTo work with 'Date' objects?
https://wiki.servicenow.com/index.php?title=GlideDateTime#compareTo.28o.29


ahammoud
Tera Guru

You're right, I had to change my Variable to a Date/Time variable, and use GlideDateTime() instead of GlideDate(). What was happening in the first line is that it was grabbing the variable value as a string, so I changed to set a new GlideDateTime value taken from the user defined variable. And it worked, the message displays if the request is within 7 days; but I want the business rule to stop the user from proceeding and submitting the request and return them (or keep them) on the same screen :

var date = new GlideDateTime(current.variables.delivery_date); //grabbing the current date specified by user

var date2 = new GlideDateTime(); //taking today's date
date2.addDays(+7); //adding 7 days to today's date

var result = (date.compareTo(date2));

if(result == '-1'){
gs.addInfoMessage('Please allow minimum 7 days for delivery');
}


Glad this corrected your issue, please mark this post as 'Answered' so others do NOT waste time finding a solution.