Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

How to calculate difference between two dates in hours ?

coolsaurabh
Tera Contributor

How to calculate difference between two dates in hours ?

1 ACCEPTED SOLUTION

markus_schaer
Tera Guru

Hi Sourabh



Here is an example on how to get the difference between two GlideDateTime objects and convert the result to hours:



var start = new GlideDateTime("2016-08-28 09:00:00");


var end = new GlideDateTime("2016-08-31 08:10:00");



// Duration in hours


var dur_seconds = gs.dateDiff(start, end, true); // returns the number of seconds as String


var dur_hours = Math.round(dur_seconds / 3600); // Math.round() is optional and will round the number to the nearest integer


gs.print(dur_hours); // *** Script: 71



This is a second example with the dedicated class GlideDuration. This class does not have a function to calculate hours (only days), but it can be useful to work with durations in general:



var start = new GlideDateTime("2016-08-28 09:00:00");


var end = new GlideDateTime("2016-08-31 08:10:00");



// Duration in days


var dur = GlideDateTime.subtract(start, end); // returns a GlideDuration object


gs.print(dur.getDisplayValue()); // *** Script: 2 Days 23 Hours 10 Minutes


gs.print(dur.getDayPart()); // *** Script: 2


gs.print(dur.getRoundedDayPart()); // *** Script: 3



Best regards


Markus


View solution in original post

11 REPLIES 11

Thanks a lot for this script! Was really helpful...

Hi All,

I have strange issue, I am trying to find out the duration between two date field on change record and get it in hours.

When I try to run the below code from background script it gives me the accurate result, below is the code snippet

var gr = new GlideRecord('change_request');
gr.addEncodedQuery('number=CHG0055112');
gr.query();

while(gr.next())
{

var start = new GlideDateTime(gr.start_date);
var end = new GlideDateTime(gr.end_date);
var dur_seconds = gs.dateDiff(start, end, true);
var dur_hours = Math.round(dur_seconds / 3600);

gs.print(dur_hours + " Hours");

}

*** Script: 5 Hours

 

But if I try the similar code from the email script it is giving me 0 hours.

Note: Any duration is less than 24 hours I am getting 0 hours as my output, if number of hours are more than 24 then I am getting the accurate result even from the email script.

Below is my email script:

var start = new GlideDateTime(current.start_date);
var end = new GlideDateTime(current.end_date);

var dur_seconds = gs.dateDiff(start, end, true);
var dur_hours = Math.round(dur_seconds / 3600);

gs.print(dur_hours + " Hours");

 

Please let me know if I am missing something here