- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-08-2017 05:12 AM
How to calculate difference between two dates in hours ?
Solved! Go to Solution.
- Labels:
-
Personal Developer Instance

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-08-2017 07:49 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-23-2018 08:41 PM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎09-28-2021 08:25 AM
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