Client Script to Populate Date based On Change of Field not Saving correct date

richelle_pivec
Mega Guru

I have built a script using the "useful field script" provided in the ServiceNow Product Documentation to populate a date field (u_resolution_date) when the Incident State (u_incident_state) field is changed to "Resolved." (value= 6).

The script works great to add the date on change of the Incident State to Resolved. However, as soon as I Save or Submit the Incident, it converts the date to yesterday's date at 7:00 p.m. The Date/Time format conforms to the one that I use throughout our instance (DD/MM/YYYY HH:SS:MM a), so I don't think that has anything to do with it.

Here is the Client Script:

Name: Populate Resolved Date Field

Type: OnChange

Field name: Incident state

Script:

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

    //Type appropriate comment here, and begin script below
   
IncidentState = g_form.getValue('incident_state');

{
        if (IncidentState == 6)    
 
  {

var ajax =new GlideAjax('MyDateTimeAjax');
ajax.addParam('sysparm_name','nowDateTime');
ajax.getXML(function(){
      g_form.setValue('u_resolved_date', ajax.getAnswer());
}
);
    }

}
}

Here is the Script Include:

Name:

MyDateTimeAjax

Client callable: True

Script:

// Be sure the "Client callable" checkbox is checked

var MyDateTimeAjax =Class.create();

MyDateTimeAjax.prototype= Object.extendsObject(AbstractAjaxProcessor,{

  nowDateTime:function(){

      return gs.nowDateTime();}});

Also of note, I have a Business Rule that calculates the Duration to Resolve. I just (today) changed it to point to the new u_resolved_date field to get its "end date." This seems to be calculating correctly and using the correct time (before the conversion to yesterday's date at 7:00 p.m.

Here's the business rule:

Name: Calculate Duration of Resolved

Run at server

function onBefore(current, previous) {  

    //This function will be automatically called when this rule is processed.        

gs.include('DurationCalculator');  

var time_elapsed = executeSample(current.opened_at,current.u_resolved_dated);  

var workday = 36000;  

var time_elapsed_1 = time_elapsed/workday;  

time_elapsed = time_elapsed_1.toFixed(1);  

current.u_incident_to_resolve_duration = time_elapsed;  

}  

function executeSample(sDate,eDate) {  

  // First we need a DurationCalculator object.  

var dc = new global.DurationCalculator();  

// The above sample is useful in limited cases. We almost always want to  

// use some schedule in a duration computation, let's load a schedule.  

addSchedule(dc);  

// Compute a duration using the schedule. The schedule  

// specifies a nine hour work day. The output of this is 36000 seconds, or  

// a ten hour span.  

dur = dc.calcScheduleDuration(sDate,eDate);  

gs.info("calcScheduleDuration with schedule with Dynamic Values: " + dur);  

return dur;  

}  

function addSchedule(durationCalculator) {  

  //   Load the "M-F Workday" schedule into our duration calculator.  

var scheduleName = "M-F Workday";  

var grSched = new GlideRecord('cmn_schedule');  

grSched.addQuery('name', scheduleName);  

grSched.query();  

if (!grSched.next()) {  

gs.log('*** Could not find schedule "' + scheduleName + '"');  

return;  

}  

  durationCalculator.setSchedule(grSched.getUniqueValue());  

}

Any ideas on why the date is converting like this?

thanks,

Richelle

8 REPLIES 8

divya mishra
Tera Guru

Hey Richelle,



Replace line 14 and 15 as :


ajax.getXML(getDate);


function getDate(response) {


    var answer = response.responseXML.documentElement.getAttribute("answer");


alert(answer);  


g_form.setValue('u_resolved_date', answer);


}




post me your feedback


Please Hit ✅Correct, ��Helpful, or ��Like depending on the impact of the response


Have a lovely day ahead




Regards,


Divya Mishra


Alas, that did not work. It added a pop-up with the Resolved Date after the Incident State changed to Resolved. After dismissing that, and clicking Save, the Resolved Date reverted back to yesterday's date with 7:00 p.m.



I did get this error at the function getDate(response) line:



function error.png



Richelle


The general best practice for what you're doing is to not do it with a client script.


Set the resolved date with a business rule instead that runs before the calculation business rule.


With the client script if someone changes the state through another method it will not calculate properly.



If you have to do it with a client script, create a temporary business rule that sets the resolved date.


See if the date maintains.


If the date maintains chances are you may have another client script running.


If the date does not maintain, then you may have another business rule running changing the value.



And I'm not sure if it's just in your example but this line has a misspelling


executeSample(current.opened_at,current.u_resolved_dated




I have no objection to using a business   rule. I thought it had to be a client script.


I did see that misspelled reference in the business rule, and I have fixed it. Thanks for the good catch.



I've worked on the business rule a bit this morning, and I did get one to work. However, it had the same behavior as the client script. It populated the date, but upon save it changed the date to the previous day at 7:00 p.m.


Now I'm wondering if something else is conflicting with it. However, it's a brand new field, so I can't imagine what could possibly be having a conflict with it.



Here's the BR I got to work:



Name: Set Resolve Date


Run at: Server


Order: 50 (Before the Calculate Duration to Resolved BR which is set at 100)



Condition: current.incident_state.changes() && (current.incident_state == 6)



Script:


                  function executeRule(current, previous /*null when async*/) {


                            g_form.setValue('u_resolved_date', getnowDateTime());  



                      }




Thanks,



Richelle