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

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

This script worked great! Thanks so much for your help!

How would I make this only count business days? Would I need to use the script include to do that? Thanks

@Aaron Schmid Yes. Need to use GlideSchedule.

1. Create a new Schedule (System Scheduler > Schedules > Schedules).

Name: Weekdays excluding Holidays

Child Schedule: U.S. Holidays
find_real_file.png

2. Add "Schedule Entries"

All day: Check

Repeats: Every Weekday (Mon-Fri)

find_real_file.png

Have to use this schedule in Script Include.

Sorry, have to go into a meeting. Get back to this later.

Hitoshi Ozawa
Giga Sage

Note, I'm calculating using 14 business days including time.

Client Script:

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
	var startDate = getDateFromFormat(newValue, g_user_date_time_format);
    var ajax = new GlideAjax('ClientDateTimeUtils');
    ajax.addParam('sysparm_name', 'getNowDateTimeDiff');
    ajax.addParam('sysparm_start_date', startDate.toString());
    ajax.getXMLAnswer(function(answer) {
        if (answer.length > 0) {
            g_form.setValue('u_mwo_late_request', (answer == 'true'));
        }
    });
}

Script Include:

var ClientDateTimeUtils = Class.create();
ClientDateTimeUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
    getNowDateTimeDiff: function() {
        try {
            var startDate = this.getParameter('sysparm_start_date');
			startDate = parseInt(startDate);

			var today = new GlideDateTime();

            var days = 14;
            var dur = new GlideDuration(60 * 60 * 24 * 1000 * days);
            var schedule = new GlideSchedule('fcf88f1097e2011086d3b4b3f153af18');  // sys_id of schedule "Weekdays excluding Holiday!"
            var end = schedule.add(today, dur);
            return (startDate < end.getNumericValue()).toString();
        } catch (e) {
            return e.message;
        }
    },
    type: 'ClientDateTimeUtils '
});

Execution results:

Case 1: Not within 14 business days

find_real_file.png

Case 2: Within 14 business days

find_real_file.png