How to compare sys_created_on date with another field using client script

divyanaraya
Tera Contributor

Hi,

 

 We have logic to implement that for the records whose created date is greater than 2 Oct,2024 ,  when user selects a field as Contract , another field is updated as valid.

If created date is lesser than 2 Oct,2024  and user selects as Contract, field should get updated as invalid.

Please suggest, how do I do these date comparison on an 'On Change' client script.

I have tried below code but it displays null value for created date.

 

var created_date1 = g_form.getValue('sys_created_on');
var old_date = new Date('2024-10-02T00:00:00Z');
var createdDate2 = new Date(created_date1);
//alert(createdDate2)   ---- This results in null value

    if (newValue == 'Contract')
    {
     if (created_date1 > old_date)
        alert ('valid');
      else if (created_date1< old_date)
       alert('invalid');
    }
2 REPLIES 2

Brad Bowman
Kilo Patron
Kilo Patron

This approach should get you closer:

function onLoad() {
	var created_date1 = getDateFromFormat(g_form.getValue('sys_created_on'), g_user_date_time_format);
	var old_date = getDateFromFormat('2024-10-02 00:00:00', g_user_date_time_format);
	if (newValue == 'Contract') {
        if (created_date1 > old_date) {
            alert ('valid');
	    } else { 
        	alert('invalid');
		}
    }
}

I changed the if block to make the possibility of created_date1 = old_date 'invalid', rather than not accounted for.

ersureshbe
Giga Sage
Giga Sage

Hi, 

I recommend utilizing a ServiceNow 'Database View' to filter your records instead of creating a script. This approach will facilitate the preparation of reports and dashboards.

 

Regards,
Suresh.