Populate Date Field with Future Date in Form

HannahH
Tera Contributor

Hi Everyone.

 

I want to create a field on a form that will show a projected date. I want the Projected Build Date to be 14 days from the day of the request but I want the end date to fall on a weekday. I am new to javascript and ServiceNow so any help is very appreciated. 

Currently I have a Client Script:

function onChange(control, oldValue, newValue, isLoading) {

var gdt = new GlideAjax("SERV_SetFutureDate");

g_form.setValue("projected_server_build",gdt);

}

 

And a script include:

MyDateTimeAjax = Class.create();

MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,

{ nowDateTime: function ()

{
var nd = new GlideDateTime(gs.nowDateTime());
gs.log('current date is :'+nd);
var fd = new GlideDateTime(nd);
fd.addDays(14);
gs.log('future date will be:'+fd);

return fd;

}

});
1 REPLY 1

Alex Rose
Tera Guru

You can use the getDayOfWeek() (docs here) function on your date to check if your future date will land on a weekend, and then add or subtract days to it to make it not fall on a weekend.

 

e.g.

if(fd.getDayOfWeek() == 6) // If future date falls on a Saturday
{
fd.addDays(2) // Add 2 days, making it Monday
}