javascriptgoogle-visualizationtimespantimeofday

How do I make a number of milliseconds into a timespan for use in Google Charts?


I have a column that is number of milliseconds that I'd like to use in a Google Charts chart to represent a duration. How do I turn that number into a time span?


Solution

  • In Google Charts, a time span can be represented using the timeofday type, which will allow you to add two times and get a third, and make charts automatically format things properly. A timeofday is actually an array with four elements: hours, minutes, seconds, and (optionally) milliseconds. See this page's explanation of the timeofday under the type property for a DataTable's cols.

    Each field of the timeofday has to be within the bounds of that that type of increment; you can't dump your whole timespan into the milliseconds field and call it a day, because anything over 999 is out-of-bounds.

    You can use this function to turn a millisecond time span into a timeofday:

    function toTimeSpan(milliseconds)
    {
        var timespan = [0, 0, Math.floor(milliseconds / 1000), milliseconds % 1000];
    
        // Minutes
        if (timespan[2] >= 60)
        {
            timespan[1] = Math.floor(timespan[2] / 60);
            timespan[2] %= 60;
    
            // Hours
            if (timespan[1] >= 60)
            {
               timespan[0] = Math.floor(timespan[1] / 60);
               timespan[1] %= 60;
            }
        }
    
        return timespan;
    }
    

    A caveat: I don't think a timeofday will allow you to hold a span greater than 24 hours. If you need that functionality, you may need to use a number column and write your own formatting.