calculate date field with current date

abhisek
Tera Contributor

Hi All,

 

I have a date variable (for example, 'termination1') which is storing future date, in the catalog item. Now I have created another date variable (for example, 'termination2'). Now I have to calculate the difference between 'termination1' and current date and that output I have to set in the 'termination2' variable.

Can anyone please help me out how can I achieve it.

 

Thanks&Regards,

Abhisek Chattaraj.

3 REPLIES 3

Danish Bhairag2
Tera Sage
Tera Sage

Hi @abhisek  ,

 

if you are expecting the diff in days then you can try the below logic by creating a BR or if its on Catalog Item then creating an on change client script from which u can call a script include & execute below code.

 

var gdt = new GlideDateTime(current.termination1); // if its called from client script kindly chnage from current to the variable where u will be storing date
var nowTime = new GlideDateTime();
var duration = GlideDateTime.subtract(nowTime, gdt);
var days = duration.getDayPart();

current.termination2 = days;
current.setWorkflow(false);
current.update()

 

 

Please mark my answer helpful & accepted if it helps you resolve your query.

 

Thanks,

Danish

RAMANA MURTHY G
Mega Sage
Mega Sage

Hello @abhisek ,

Do you want the difference between termiation1 and today's date in numeric format or in date format?

If you want a numeric format Ternimation2 field should be number type.

Please mark my answer helpful  & correct if it helps you
Thank you

G Ramana Murthy
ServiceNow Developer

RAMANA MURTHY G
Mega Sage
Mega Sage

Hello @abhisek  ,

Please find below code 

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

	var ternimation1 = new GlideDuration();
	ternimation1.setValue(current.u_termination1);
	var currentDate = new GlideDuration();
	
        var diff = currentDate.subtract(ternimation1);
	current.u_termination2 = diff.getDayPart();      // u_termination2 field is number field here
  //      current.u_terminaton2 = diff.getDisplayValue();     if u_termination2 file is string field  getDisplayValue displays Days hours 
      //  current. u_terminaton2 = diff.getNumericValue();     it gives total minutes  in numerical format

})(current, previous);

 

Please mark my answer as correct and helpful, if it resolves your query.

Thank you

Please mark my answer helpful  & correct if it helps you
Thank you

G Ramana Murthy
ServiceNow Developer