Prevent past date and time to enter in ServiceNow

swathi44
Tera Contributor

I want to prevent user to enter past date and time to both 'starts' and 'ends' fields and starts should not be greater than ends. I tried many ways and all are working but the issue is time zone. My system is IST and Instance is CET. Consider now time is Aug 7th, 2 PM CET. When I enter Aug 7th, 3 PM future time also it is showing error as it is taking IST time. To avoid error I need to enter greater than 5:30 PM in starts field. But that is not correct.

Please help me with the solution. Thank you in Advance!

3 REPLIES 3

Brad Bowman
Kilo Patron
Kilo Patron

Samaksh Wani
Giga Sage
Giga Sage

Hello @swathi44 

 

Plz go through the link below :-

 

https://www.servicenow.com/community/itsm-forum/how-to-prevent-user-to-select-past-date-and-time-of-...

 

 

Plz Mark my Solution as Accept and Give me thumbs up, if you find it helpful.

 

Regards,

Samaksh

Claude DAmico
Kilo Sage

Here is something I picked up when I started learning just how frustrating dates and times could be.

  • .getDisplayValue('date_time_field'); should return the displayed value per the user running the code which should be the current user and their timezone in most cases
  • .getValue('date_time_field'); should return the system value of the date/time field.
  • GlideDateTime() without parameters returns the current UTC date/time
    • .getDisplayValue() for GDT will convert to the user's timezone
  • Date() without parameters returns the current system date/time

GlideDateTime() is server-side only so use GlideAjax to call a Script Include if you plan on using it. Date() should be able to be used in either Client or Server-side scripting.

 

You can convert both to milliseconds to compare.

  • GlideDateTime().getNumericValue(); //last three digits will always be zeros e.g. 1691419178000
  • Date().valueOf(); //e.g. 1691419178846

Convert Date() to GlideDateTime()

 

var date = new Date();
var gdt = new GlideDateTime(date.getFullYear() + "-" + ("0" + (date.getMonth() + 1)).slice(-2) + "-" + ("0" + date.getDate()).slice(-2) + " " + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2) + ":" + ("0" + date.getSeconds()).slice(-2));

 

Putting all this together, you should be able to accomplish what you need and could look something like this.

 

var currDate = new GlideDateTime();
currDate = new GlideDateTime(currDate.getDisplayValue()); //convert to user's timezone
var currMil = currDate.getNumericValue();

var startDate = new GlideDateTime(current.getDisplayValue('date_time_field'))
var startMil = startDate.getNumericValue();

var endDate = new GlideDateTime(current.getDisplayValue('date_time_field'));
var endMil = endDate.getNumericValue();

if(startMil < currMil || endMil < currMil || endMil < startMil){
     return "error";
}

 

 

Claude E. D'Amico, III - CSA