How to set Calculated Value for Duration (or any other date/time) field

Valon Sheremeti
Kilo Guru

Hi,

I am unsuccessfully trying to dynamically set/calculate 'duration' field value based on difference between opened_at and closed_at fields   in an scoped application.

I tried using script below for 'calculated value' but no luck.

Thanks in advance.

(function calculatedFieldValue(current) {

var startDate = current.opened_at;  

var endDate = current.closed_at;  

var duration = GlideDateTime.subtract(startDate, endDate);

return duration;

})(current);

I tried also:

return GlideDateTime.substract(opened_at,closed_at);

but no luck - -my calculated field show <empty> value.

Thank you.

1 ACCEPTED SOLUTION

Can we try something like this


(function calculatedFieldValue(current) {

var startDate = new GlideDateTime(current.opened_at);


var endDate = new GlideDateTime(current.closed_at);


var duration = GlideDateTime.subtract(startDate, endDate);  


return duration.getDisplayValue();


})(current);



Please mark my response as correct and helpful if it helped solved your question.
-Thanks

View solution in original post

20 REPLIES 20

Can you try with below if condition?



if(endDate.getDisplayValue() == ''){


Hello Mohammed


Please attach a screenshot of your feild(your calculated value/required duration feild)


(function calculatedFieldValue(current) {


var startDate = new GlideDateTime(current.u_today_s_date); //what is this field??


var endDate = new GlideDateTime(current.u_rca_due_date);


      if(endDate == ''){


              var today = new GlideDateTime();


              var result = GlideDateTime.subtract(startDate, today);


              return result.getDisplayValue();


      }


      else{


              var duration = GlideDateTime.subtract(startDate, endDate);


              return duration.getDisplayValue();


      }  


})(current);


return '';   // return the calculated value // why this return statement??



Please mark my response as correct and helpful if it helped solved your question.
-Thanks

Hi Prateek,


Thank you for your quick response. I removed the last line. The field "u_today_s_date" is today's date. I am trying to calculate the number of days between today & due date (u_rca_due_date). Here are fields info:


find_real_file.pngfind_real_file.png


also calculated value should be here:find_real_file.png


Mohammed


Your feild type is glide_date but in the calculated value, we are using GlideDateTime() function. i think this is causing the issue.



Please mark my response as correct and helpful if it helped solved your question.
-Thanks