How to subtract two date-time fields on a form

JJG
Kilo Guru

Hello,

I have a Ui action button, when pressed it should take the date-time value from the clocked_in field and subtract the date-time value of the clocked_out field on my form. Then It should take the result, turn it into a string and then store it in the hours_worked string field. My code does not work, what am I missing?


var diff = GlideDateTime.subtract(current.clocked_in, current.clocked_out);
var diffString = diff.toString();

current.hours_worked = diffString;
current.update();
action.setRedirectURL(current);

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

According to the docs, you need to send the display values as args to GlideDateTime - subtract.

Try this:

var diff = GlideDateTime.subtract(current.clocked_in.getDisplayValue(), current.clocked_out.getDisplayValue());
var diffString = diff.getDisplayValue();

current.hours_worked = diffString;
current.update();
action.setRedirectURL(current);

View solution in original post

4 REPLIES 4

Chuck Tomasi
Tera Patron

According to the docs, you need to send the display values as args to GlideDateTime - subtract.

Try this:

var diff = GlideDateTime.subtract(current.clocked_in.getDisplayValue(), current.clocked_out.getDisplayValue());
var diffString = diff.getDisplayValue();

current.hours_worked = diffString;
current.update();
action.setRedirectURL(current);

Utpal Dutta1
Mega Guru

Hey JJG,

Modify below given script according to your need: 

 

Below script is for comparing two date fields but you can use it for addition and substraction as well.

 

if ((!current.u_date1.nil()) && (!current.u_date2.nil())) { 
  var start = current.u_date1.getGlideObject().getNumericValue(); 
  var end = current.u_date2.getGlideObject().getNumericValue(); 
  if (start > end) {
    gs.addInfoMessage('start must be before end');
    current.u_date1.setError('start must be before end') ;
    current.setAbortAction(true);
 } }


If i was able to help you out then please mark my comment Helpful and Correct.

 

Thanks and Regards:

Utpal Dutta

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

I would recommend to store the difference in a duration field and not string field; use below sample code to set the value in the duration field

var clockedIn = new GlideDateTime(current.clocked_in);
var clockedOut = new GlideDateTime(current.clocked_out);
var diffSeconds = GlideDateTime.subtract(clockedIn, clockedOut);

var milliseconds = diffSeconds*1000;

current.hours_worked.setDateNumericValue(milliseconds);
current.update();
action.setRedirectURL(current);

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

hongsok
Tera Contributor

Hi Ankur,

 

I have a similar requirement but need to get the result in Business day. Could you please give me a clue?

 

Regards,

Hong