How to get server date via script include, and compair to another date on client script

AlbertoMedeiros
Tera Contributor

Hello. Recently I'm working on an adjustment that envolve comparission two dates. A specific catalog item should not allow any user to open a new request via service portal, if the current date is bigger than 24th day of the current month.

 

First, I'd created this validation on a client script, but testing I have identified that if date/time of users devices are not equal of the current date/time (for example, not automatic on windows), this code could fail on his validation.

 

    var today = new Date();
            if (today.getDate() >24) {
                g_form.addErrorMessage('Data Limite para abertura desta solicitação excedida.');
                return false;

 

So now, I need to create a GlideAjax and get the server date, to compare and validate if the current date is bigger de 24th.

 

Does anyone had developed something similar to this? Or know how it could work?

Best regards,

Alberto.

1 ACCEPTED SOLUTION

Bailey Pratt
Giga Contributor

Here is an example of how you can get the server date via a Script Include and compare it to another date in a Client Script in ServiceNow:
1. Script Include:

var ServerDate = Class.create();
ServerDate.prototype = {
initialize: function() {
},
getDate: function() {
var gr = new GlideRecord('sys_calendar');
gr.get("sys_id", "1");
var d = gr.getValue('current');
return d;
}
};

2. Client Script:

var targetDate = new GlideDate();
targetDate.setValue("2023-02-07");

var serverDate = new ServerDate().getDate();
if (targetDate.compareTo(serverDate) >= 0) {
// targetDate is greater than or equal to serverDate
gs.addInfoMessage("The target date is greater than or equal to the server date");
} else {
// targetDate is less than serverDate
gs.addInfoMessage("The target date is less than the server date");
}

Note: The ServerDate Script Include and the Client Script should be added to your ServiceNow instance via the UI.

 

You can Thanks me Here: Alight motion Pc

View solution in original post

5 REPLIES 5

capcuttempl
Mega Contributor

If you're trying to get the server date through a script include and compare it to another date in a client script, it's easier than you might think. By using a script include to fetch the server date and then passing that date to your client script, you can easily perform your date comparison. For more tips on making your scripts work smoothly, check out this guide on https://alightmotionclub.in/how-to-use-preset-in-alight-motion/. It’s all about simplifying your workflow and making the most out of your tools!