How to check if a date is less than or equal to a stored date in servicenow?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-01-2024 05:43 AM
Dear experts,
How to check if a given date is less than or equal to a stored date? We have a date field in catalog item. This is being sent over to a script include. My requirement is, there is a stored date in a custom table. I want to compare the user selected date with the stored date and see if the user selected date less that the stores date. Looks like the < operator does not work with date fields. Please advice.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-01-2024 05:56 AM - edited 09-01-2024 06:01 AM
Hi @gowdash ,
Generally it should work, can you check are both fields of the same data type.
Below is the example,
var date1 = new GlideDateTime('2024-09-31 12:00:00'); // First date with time
var date2 = new GlideDateTime('2024-08-01 12:00:00'); // Second date with time
if (date1.before(date2)) {
gs.info('Date1 is before Date2');
} else if (date1.after(date2)) {
gs.info('Date1 is after Date2');
} else {
gs.info('Date1 is the same as Date2');
}
if(date1 < date2){
gs.info('Date1 is before Date2');
}else if(date1 > date2){
gs.info('Date1 is after Date2');
}else {
gs.info('Date1 is the same as Date2');
}
Output:
*** Script: Date1 is after Date2
*** Script: Date1 is after Date2
IF it's GlideDate()
var gd1 = new GlideDate();
gd1.setValue('2021-06-21');
gs.info(gd1.getDisplayValue());
var gd2 = new GlideDate();
gd2.setValue('2021-05-21');
gs.info(gd2.getDisplayValue());
if(gd1 < gd2){
gs.info('gd1 is before gd2');
}else{
gs.info('gd2 is before g1');
}
Output;
*** Script: 21/06/2021
*** Script: 21/05/2021
*** Script: gd2 is before g1
If this information helps you, kindly mark it as Helpful and Accept the solution.
Regards,
Najmuddin.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-01-2024 07:31 AM
Hi @gowdash ,
Please find the below code-
function isDateLessOrEqual(givenDate, storedDate) {
var gdGivenDate = new GlideDateTime(givenDate);
var gdStoredDate = new GlideDateTime(storedDate);
// Check if the given date is less than or equal to the stored date
if (gdGivenDate.compareTo(gdStoredDate) <= 0) {
return true;
} else {
return false;
}
}
// Example usage
var userSelectedDate = '2024-09-01 12:00:00';
var storedDateInTable = '2024-09-02 00:00:00';
var result = isDateLessOrEqual(userSelectedDate, storedDateInTable);
if(result) {
gs.info("The given date is less than or equal to the stored date.");
} else {
gs.info("The given date is greater than the stored date.");
}