How do I convert a GlideDuration field to number of seconds?

peterdelf
Giga Expert

I'm trying to convert the delivery_time field from a catalogue item to the number of seconds, but I'm going round in circles with GlideDuration and GlideDateTime values.   I know the underlying storage of a GlideDuration object is either seconds or milliseconds.   How do I get to that value?

I've tried the following in background scripts:

var a = new GlideRecord('sc_cat_item');

a.get("0d68ec6edb5c070039f7f70dbf96191d");

gs.print(a.delivery_time.toString());

var b = new GlideDateTime(a.delivery_time.toString());

gs.print(b);

var c = new GlideDuration(0);

gs.print(c.toString());

var d = GlideDateTime.subtract(c, b);

gs.print(d.toString());

Which gives me:

*** Script: 1970-01-03 00:00:00

*** Script: 1970-01-03 00:00:00

*** Script: 1970-01-01 00:00:00

*** Script: 1970-01-03 00:00:00

But I'm going round in circles

Been referring to this - https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDurationGlideDuration_St...

1 ACCEPTED SOLUTION

Chuck Tomasi
Tera Patron

Hi Peter,



Use the GlideDuration method getByFormat() to format it in to YYYY-MM-dd hh:mm:ss



and then you can feed that to GlideDateTime() and use getNumericValue() to get the number seconds (since 1970).



https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDateTimeGetNumericValue



https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDurationGetByFormat_Stri...


View solution in original post

10 REPLIES 10

Chuck Tomasi
Tera Patron

Hi Peter,



Use the GlideDuration method getByFormat() to format it in to YYYY-MM-dd hh:mm:ss



and then you can feed that to GlideDateTime() and use getNumericValue() to get the number seconds (since 1970).



https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDateTimeGetNumericValue



https://developer.servicenow.com/app.do#!/api_doc?v=jakarta&id=r_ScopedGlideDurationGetByFormat_Stri...


Hi Chuck,


That's perfect thanks!


Seems really backwards that you need to go GlideDuration->GlideDateTime to get a duration value in seconds!



BTW.   i needed to divide by 1000 as the value given is in milliseconds.


You can cut out the GlideDateTime as well.  .getNumericValue() can be run on a GlideDuration to get the number of milliseconds.

var a = new GlideDuration('3:45:67');

gs.log(a.getNumericValue()/1000);  // milliseconds divided by 1000 = seconds

//returns 13500 seconds