How to convert Duration to seconds in scoped app?

Priya Shekar
Giga Guru

Hi All,


As functions calDateDiff and dateDiff is not allowed in scoped app, I am trying to use "GlideDateTime.subtract" in my code like below.

"var gdt1 = new GlideDateTime("2011-08-28 09:00:00");

var gdt2 = new GlideDateTime("2011-08-31 08:00:00");

var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2

gs.info(dur.getDisplayValue());"


Variable "dur" returns duration. I need to convert this duration to seconds.

Tried using getNumericValue to convert, but GlideDatetime function should have date and time format as parameter.


So is there any solution for this issue?


Thanks,

Priya

4 REPLIES 4

john_roberts
Mega Guru

GlideDuration.getNumericValue() returns the duration in milliseconds.   This should work.



var gdt1 = new GlideDateTime("2011-08-28 09:00:00");


var gdt2 = new GlideDateTime("2011-08-31 08:00:00");



var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2



gs.info("diff display: {0}", dur.getDisplayValue());


gs.info("diff seconds: {0}", dur.getNumericValue() / 1000);


Thanks John..


The solution works as expected..



Regards,


Priya


mak1A4
Tera Guru

For anybody who doesn't want to get the duration between two date times and only want to convert the value of a duration field to seconds in a scoped application the solution is to convert the string you get as value from the duration field to GlideDateTime and then use the function getNumericValue() from the gdt.

var durationStr = gr.getValue("duration_field");
//durationStr = "1970-01-01 05:54:00"

var gdt = new GlideDateTime(oneOffEffortStr);
var durationInSeconds = gdt.getNumericValue() / 1000;
//durationInSeconds = 21240

This almost worked for me, but I had to append .getValue() when converting the duration field to GlideDateTime.  Here's my example of what finally worked in my case, which was auto populating the end time based on the selected start time and specified duration:

(function executeRule(current, previous /*null when async*/ ) {

    // Add your code here

    // calculates the end time of an activity based on the start time and duration

    var startTime = new GlideDateTime(current.variables.access_start.getValue()); // getting start time
    var dur = new GlideDateTime(current.variables.how_long.getValue()); // getting duration and converting to GlideDateTime
    dur = dur.getNumericValue()/1000; // calculating the total duration in seconds
    //gs.addInfoMessage(dur);
	
	startTime.addSeconds(dur); // add the seconds to the start time to calculate end time

	current.variables.access_end = startTime.getValue(); // set the end time
	//gs.addInfoMessage(startTime);

    gs.addInfoMessage("End time automatically adjusted based on start time and duration");

})(current, previous);