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.

Script to convert String to Duration

Akshay Harkulka
Tera Contributor

Hello Team,

 

I Have created one background script to insert SLA definition record in 'contract_sla' table.

 

I am able to create a record in said table but I need a code to set duration value.

 

So, could you please help me with the script to convert String value (5 Hrs.) to Duration value in SLA Definition Table.

 

For example :

Resolution Time : 5 (Value is in Hrs)

 

AkshayHarkulka_1-1673597310441.png

 

 

@script 

1 ACCEPTED SOLUTION

newhand
Mega Sage

@Akshay Harkulka 

 

You can create a GlideDuration object by below function ,

but you should format your string to the right format(d HH:mm:ss)   <-- i think this is not a problem for you.

 

GlideDuration(String displayValue)

Instantiates a GlideDuration object with the specified duration display value.
Parameters
Name Type Description
displayValueStringDuration value.

Format: d HH:mm:ss where "d" is number of days.

 

 

var duration = new GlideDuration('3 12:00:00');
var duration2 = new GlideDuration('3:00:00');
var answer = duration.add(duration2);
gs.info(answer.getDisplayValue());


output

3 Days 15 Hours

 

Please mark my answer as correct and helpful based on Impact.

View solution in original post

4 REPLIES 4

Omkar Kumbhar
Mega Sage

Hello @Akshay Harkulka ,

Please find the below code.

s2t=function (t){
var duration= parseInt(t/86400)+'d '+(new Date(t%86400*1000)).toUTCString().replace(/.*(\d{2}):(\d{2}):(\d{2}).*/, "$1h $2m $3s");
gs.print(duration);
return duration;
}

s2t(1236768);

*** Script: 14d 07h 32m 48s

you can pass the string value in s2t (stringoutput)

 

If I was able to help you with your case, please click the Thumb Icon and mark as Correct.

Thanks @Omkar Kumbhar 

newhand
Mega Sage

@Akshay Harkulka 

 

You can create a GlideDuration object by below function ,

but you should format your string to the right format(d HH:mm:ss)   <-- i think this is not a problem for you.

 

GlideDuration(String displayValue)

Instantiates a GlideDuration object with the specified duration display value.
Parameters
Name Type Description
displayValueStringDuration value.

Format: d HH:mm:ss where "d" is number of days.

 

 

var duration = new GlideDuration('3 12:00:00');
var duration2 = new GlideDuration('3:00:00');
var answer = duration.add(duration2);
gs.info(answer.getDisplayValue());


output

3 Days 15 Hours

 

Please mark my answer as correct and helpful based on Impact.

Thanks @newhand