is it a bug? for GlideDateTime.subtract

Chris45
ServiceNow Employee
ServiceNow Employee

for below code

var dur = GlideDateTime.subtract(new GlideDateTime("2025-03-28 18:04:55"), new GlideDateTime("2025-03-29 18:04:55"));
gs.info("dur: " +dur.getByFormat('hh:mm:ss'));

dur_seconds = GlideDateTime.subtract(new GlideDateTime("2025-03-28 18:04:55"), new GlideDateTime("2025-03-28 18:04:55"));
gs.info("dur: "+dur.getByFormat('hh:mm:ss'));

 

expect first print 24:00:00, and second to be 00:00:00, but both print

12:00:00

 is this correct? confused

1 ACCEPTED SOLUTION

@Chris45 

ooh, can try with Convert the duration to seconds and then format manually.

var dur = GlideDateTime.subtract(new GlideDateTime("2025-03-28 18:04:55"), new GlideDateTime("2025-03-29 18:04:55"));
var totalSeconds = dur.getDurationValue(); 

var hours = Math.floor(totalSeconds / 3600); // Get hours
var minutes = Math.floor((totalSeconds % 3600) / 60); // minutes
var seconds = totalSeconds % 60; //seconds

gs.info("dur: " + (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds));

 

View solution in original post

10 REPLIES 10

Chris45
ServiceNow Employee
ServiceNow Employee

how to get only the time part 'hh:mm:ss' format for subtract? 

Hi @Chris45 
24:00:00 will be converted to the next day (next date 00:00:00) by default. Nowhere we can see the time as 24:00:00. 
The methods are working as expected

Chris45
ServiceNow Employee
ServiceNow Employee

and getByFormat('HH:MM:SS') prints different yet still unexpected result

Nilesh Pol
Tera Guru

@Chris45 

on the line:

dur_seconds = GlideDateTime.subtract(new GlideDateTime("2025-03-28 18:04:55"), new GlideDateTime("2025-03-28 18:04:55"));
gs.info("dur: " + dur.getByFormat('hh:mm:ss'));

You're subtracting the same time from itself, which results in a duration of 0. The same formatting issue happens again: you're using a 12-hour format and it will show 12:00:00 for a 0 duration because of how the getByFormat('hh:mm:ss') method works.

To get the correct 24-hour format, use the getByFormat() method but specify a 24-hour format instead of 12-hour format.

You can achieve that by using HH instead of hh.

Use the following updated code:

gs.info("dur: " + dur.getByFormat('HH:mm:ss')); // 24-hour format