The CreatorCon Call for Content is officially open! Get started here.

Using dateDiff to check if date is within 14 days from now

Aaron Schmid
Tera Contributor

I'm trying to use a client script / script include combo to find out if a date is within 14 days.

If the 'Start Date' (u_mwo_promo_start_time) is less than 14 days from now, the late request box should switch to 'true' and an alert should show.

I am not getting anything from the script include right now. I have the answer in the alert and it's just showing a 'null' value.

This is on a record producer that feeds into a custom table on a scoped application.

I got both scripts from this post: https://community.servicenow.com/community?id=community_question&sys_id=38c40be9dbd8dbc01dcaf3231f96...

 

Client Script...

find_real_file.png

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

		var cdt = newValue; //First Date/Time //g_form.getDisplayValue('u_mwo_promo_start_time');
		//var now = g_form.getValue('u_mwo_now_date');
		var dttype = 'day'; //this can be day, hour, minute, second. By default it will return seconds.
        
		var ajax = new GlideAjax('ClientDateTimeUtils');
			ajax.addParam('sysparm_name','getNowDateTimeDiff');
			ajax.addParam('sysparm_fdt', cdt);
			ajax.addParam('sysparm_difftype', dttype);
			ajax.getXML(checkDate);

		function checkDate(response){
			var answer = response.responseXML.documentElement.getAttribute("answer");
			alert(answer);
			if(answer > 14){
				g_form.setValue('u_mwo_late_request',true);
			}
		}
   
}

 

Script Include...

find_real_file.png

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

//Takes a Single Date/Time Field and returns its time difference from nowDateTime().
//params = sysparm_fdt (the first date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)
getNowDateTimeDiff: function(){
var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
var diff = gs.dateDiff(gs.nowDateTime(), firstDT, true);
var timediff = this._calcDateDiff(diffTYPE, diff);
//return "getNowDateTimeDiff: FIRST DT: " + firstDT + " -DIFFTYPE: " + diffTYPE + " -TIME DIFF: " + timediff;
return timediff;
},

Here's the alert I'm getting when I enter a date in the field...

find_real_file.png

Any help is greatly appreciated! Thanks!

1 ACCEPTED SOLUTION

Hitoshi Ozawa
Giga Sage
Giga Sage

Client Script only comparing with current date.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    try {
        var startDate = new Date();
		startDate = new Date(startDate.toLocaleDateString());
        var endDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));
		endDate = new Date(endDate.toLocaleDateString());

        var daysDiff = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
        if (daysDiff > 14) {
			g_form.setValue('u_mwo_late_request', true);
		} else {
			g_form.setValue('u_mwo_late_request', false);
		}
    } catch (e) {
        alert(e.message);
    }
}

Execution result:

1. Within 14 days.

find_real_file.png

2. Over 14 days.

find_real_file.png

 

View solution in original post

8 REPLIES 8

DrewW
Mega Sage

If all you need is to check to see if a date was entered that is 14 days from now and you do not have to account for Holidays or weekends then just have the client do all of the work

This script will check 6 months, but I'm sure you can tweak it for your application.  If its a date field use g_user_date_format instead of g_user_date_time_format.

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}
	
	//New Effective date must be less than 6 months from now.
	var newDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));
	var nowdt = new Date();
	var maxDate = new Date(nowdt.setMonth(nowdt.getMonth() + 6));
	if(newDate > maxDate){
		alert("Please pick a date that is less than 6 months from now.");
		g_form.setValue("effective_to_date", "");
	}
	
}

Hitoshi Ozawa
Giga Sage
Giga Sage

Following client script will check if the days are 14 days apart.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    try {
        var startDate = g_form.getValue('u_mwo_promo_start_time');
        if (startDate == '') {
            return;
        }
        startDate = new Date(getDateFromFormat(startDate, g_user_date_time_format));
        var endDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));

        var daysDiff = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
        if (daysDiff > 14) {
			g_form.setValue('u_mwo_late_request','Yes');
		} else {
			g_form.setValue('u_mwo_late_request', 'No');
		}
    } catch (e) {
        alert(e.message);
    }
}

Variables used:

find_real_file.png

Execution results:

1. within 14 days

find_real_file.png

2. more than 14 days

find_real_file.png

 

Hitoshi Ozawa
Giga Sage
Giga Sage

In case of using Script Include. I've added comment inline. Basically, needs to convert String to GlideDateTime and to use local time zone.

Client Script:

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
      return;
   }
		var cdt = newValue; //First Date/Time //g_form.getDisplayValue('u_mwo_promo_start_time');
		//var now = g_form.getValue('u_mwo_now_date');
		var dttype = 'day'; //this can be day, hour, minute, second. By default it will return seconds.
        
		var ajax = new GlideAjax('ClientDateTimeUtils');
			ajax.addParam('sysparm_name','getNowDateTimeDiff');
			ajax.addParam('sysparm_fdt', cdt);
			ajax.addParam('sysparm_difftype', dttype);
			ajax.getXML(checkDate);

		function checkDate(response){
			var answer = response.responseXML.documentElement.getAttribute("answer");
			alert(answer);
			if(answer > 14){
				g_form.setValue('u_mwo_late_request',true);
			} else {
				g_form.setValue('u_mwo_late_request',false);
			}
		}
  }

Script Include:

var ClientDateTimeUtils = Class.create();
ClientDateTimeUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    //Takes a Single Date/Time Field and returns its time difference from nowDateTime().
    //params = sysparm_fdt (the first date/time field), sysparm_difftype (time based format to return result. See "_calcDateDiff" function comments)
    getNowDateTimeDiff: function() {
            var firstDT = this.getParameter('sysparm_fdt'); //First Date-Time Field
            var diffTYPE = this.getParameter('sysparm_difftype'); // Date-Time Type to return the answer as. Can be second, minute, hour, day
			var today = new GlideDateTime(gs.nowDateTime()); // gs.nowDateTime() returns a String so need to convert to GlideDateTime
			firstDT = new GlideDateTime(firstDT);   // change from String to GlideDateTime
			var diff = gs.dateDiff(today, firstDT.getDisplayValue(), true);  // calculate date difference in local time zone
            return Math.floor(diff/(60*60*24));  // change second to days
    },
    type: 'ClientDateTimeUtils'
});

Execute result:

1. Within 14 days.

find_real_file.png

2. More than 14 days.

find_real_file.png

Hitoshi Ozawa
Giga Sage
Giga Sage

Client Script only comparing with current date.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    try {
        var startDate = new Date();
		startDate = new Date(startDate.toLocaleDateString());
        var endDate = new Date(getDateFromFormat(newValue, g_user_date_time_format));
		endDate = new Date(endDate.toLocaleDateString());

        var daysDiff = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
        if (daysDiff > 14) {
			g_form.setValue('u_mwo_late_request', true);
		} else {
			g_form.setValue('u_mwo_late_request', false);
		}
    } catch (e) {
        alert(e.message);
    }
}

Execution result:

1. Within 14 days.

find_real_file.png

2. Over 14 days.

find_real_file.png