Get GlideDuration value in millseconds

Curiously, ServiceNow’s GlideDuration object gives you a way to set the duration in milliseconds (i.e. passing in the millisecond value when constructing a new instance) but there’s no simple way to get back that duration expressed in milliseconds. You can get it back expressed in days, hours, minutes, and seconds in just about any format you might need, but not in total milliseconds. I recently had a use case for expressing a duration in total hours, where being able to get back a millisecond value would have been very convenient. But instead I had to get creative with string manipulation to convert the duration display value back into milliseconds. If you need to do this too, do yourself a favor and put it in a Script Include so it’s reusable.

Here’s my Script Include, which you are welcome to copy verbatim or use as inspiration for your own (at the very least, I recommend replacing “ACME” with your company’s name or initials, or just name it according to whatever convention you would normally follow at your organization):

var ACMEDurationHelper = Class.create();  
ACMEDurationHelper.prototype = {  
    initialize: function() {
    },

    // Accepts a GlideDuration object, passes back
    // total milliseconds of the duration.
    getTotalMS: function(dur) {
        var durVal = dur.getDurationValue();

        // Parse the duration value into days and time
        var durValArr = durVal.split(' ');
        var days = 0;
        if (durValArr.length == 2) {
            var days = parseInt(durValArr.shift(), 10);
        }
        var time = durValArr.shift();

        // Parse the time into hours, minutes, and seconds
        var timeArr = time.split(':');
        var hours = parseInt(timeArr[0], 10);
        var minutes = parseInt(timeArr[1], 10);
        var seconds = parseInt(timeArr[2], 10);

        // Calculate and return total milliseconds
        return days * 86400000
             + hours * 3600000
             + minutes * 60000
             + seconds * 1000;
    },

    getTotalSecs: function(dur) {
        return this.getTotalMS(dur) / 1000;
    },

    getTotalMins: function(dur) {
        return this.getTotalMS(dur) / 60000;
    },

    getTotalHrs: function(dur) {
        return this.getTotalMS(dur) / 3600000;
    },

    getTotalDays: function(dur) {
        return this.getTotalMS(dur) / 86400000;
    },

    type: 'ACMEDurationHelper'
};

If this is useful to you, drop me a comment to let me know. Cheers!