Date comparison issue

sainath3
Giga Guru

Hi All,

 

Please provide you inputs for below issue.

 

Requirement:

In our custom table we have two fields, Start Date & End Date, every time if any new record is created, it should check with existing records and make sure to add start date before the start date of existing records.

I have written OnChange client script & Script includes.

but if I enter the date as 11-12-2025.//Dec 11th

Expected output is: Please select before: 12-11-2025

Actual output: no alert it is accepting.

In my RCA:

while comparing it is considering start date as mm-dd-yyyy.

In existing there are multiple records are created.

ex: Here End user changed their date format to dd-mm-yyyy.

Fal IDStart DateEnd Date
12312-11-202531-12-2025

Sample code:

ar sdate="11-12-2025";
var gdt = new GlideDateTime(sdate);
//var dateOnly = gdt.getLocalDate();
var dateOnly=gdt.getDate();
gs.print(dateOnly);
Output: 2025-11-12//Nov 12th
6 REPLIES 6

Vishal_Jaiswal
Mega Guru

Hi @sainath3 ,

Please try the approach below once.

 

- It seems a classic Date Format issue in ServiceNow.
- When you pass a date string from the Client Side (Browser) to the Server Side (Script Include), it is sent as a simple string (e.g., "11-12-2025").
- When you use new GlideDateTime(sdate) in your Script Include, the system tries to guess the format. It often defaults to the system format (usually US: MM-dd-yyyy) rather than the User's format (dd-MM-yyyy), which causes December 11th (11-12) to be interpreted as November 12th.

Solution: Use setDisplayValue()
To fix this, do not pass the date string into the GlideDateTime constructor. Instead, create an empty object and use .setDisplayValue(). This method tells ServiceNow: "Interpret this string using the current user's date format preference."

Script Include reference:

var DateValidationUtils = Class.create();
DateValidationUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    checkStartDate: function() {
        var newDateString = this.getParameter('sysparm_start_date');
        
        // 1. Parse the incoming date using the USER'S format
        var newGDT = new GlideDateTime();
        newGDT.setDisplayValue(newDateString); // <--- THIS IS THE FIX
        
        // Get the internal system format (YYYY-MM-DD) for comparison
        var newDateInternal = newGDT.getDate().getValue(); 

        // 2. Query existing records to find the Earliest Start Date
        // NOTE: You likely need to add a filter here (e.g., for a specific Project or User)
        // Otherwise it compares against ALL records in the table.
        var gr = new GlideRecord('u_your_custom_table'); // Replace with your table name
        gr.orderBy('u_start_date'); // Order by date ascending to find the earliest
        gr.setLimit(1);
        gr.query();

        if (gr.next()) {
            var existingStartDate = new GlideDateTime(gr.getValue('u_start_date'));
            var existingDateString = existingStartDate.getDate().getValue(); // YYYY-MM-DD

            // 3. Compare the dates
            // If New Date is NOT before Existing Date (i.e., it is same or after)
            if (newGDT.compareTo(existingStartDate) >= 0) {
                
                // Return JSON object with error and the date to display
                var result = {
                    isValid: false,
                    existingDate: existingStartDate.getDisplayValue() // Return in user's format
                };
                return JSON.stringify(result);
            }
        }

        // If validation passes
        return JSON.stringify({ isValid: true });
    },

    type: 'DateValidationUtils'
});

 

Client script reference:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var ga = new GlideAjax('DateValidationUtils');
    ga.addParam('sysparm_name', 'checkStartDate');
    ga.addParam('sysparm_start_date', newValue); // Passing the raw string (e.g., 11-12-2025)
    
    ga.getXMLAnswer(function(answer) {
        var response = JSON.parse(answer);

        if (!response.isValid) {
            g_form.clearValue('u_start_date'); // Clear the invalid date
            g_form.showFieldMsg('u_start_date', 'Please select a date before: ' + response.existingDate, 'error');
            alert('Please select a date before: ' + response.existingDate);
        }
    });
}

 

Regards,

Vishal

 

yashkamde
Tera Contributor

In client script use new Date (javascript api which has inbuilt conversion and comparison of dates),
Screenshot 2025-11-25 111733.png

 

and result will be liked this,

Screenshot 2025-11-25 111745.png

Sarthak Kashyap
Mega Sage

Hi @sainath3 ,

 

I think the issue is you are not setting the value in correct formate please check the script below 

 

Client Script

Create a client script which works on your start value field and add below scirpt

function onChange(control, oldValue, newValue) {
    if (!newValue)
        return;

    var ga = new GlideAjax('CustomDateValidation');
    ga.addParam('sysparm_name', 'validateStartDate');
    ga.addParam('sysparm_start_date_display', newValue); // dd-MM-yyyy
    ga.getXMLAnswer(function(response) {
        if (response !== 'OK') {
            alert(response);
            g_form.clearValue('start_date');
        }
    });
}

 

Script include which is client callable/ GlideAjax callable 

var CustomDateValidation = Class.create();
CustomDateValidation.prototype = {
    initialize: function() {},

    validateStartDate: function() {
        var userDisplayDate = this.getParameter('sysparm_start_date_display'); 

        var gd = new GlideDate();
        gd.setDisplayValue(userDisplayDate); 
        var newStartSys = gd.getValue();     

        var gr = new GlideRecord('x_your_table_here'); 
        gr.query();
        while (gr.next()) {
            var existingStartSys = gr.getValue('u_start_date');

            if (newStartSys >= existingStartSys) {
                return "Please select a date before: " + gr.getDisplayValue('u_start_date');
            }
        }

        return "OK";
    },

    type: 'CustomDateValidation'
};

 

Please mark my answer correct and helpful if this works for you

Thanks and Regards,

Sarthak

@Sarthak Kashyap 

are you sure your script include will be called via GlideAjax?

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