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?
How do I make a number of milliseconds into a timespan for use in Google Charts?
2k Views Asked by Kenny Dewhirst At
3
There are 3 best solutions below
0
On
To expand on Kenny's answer, if you input your data as milliseconds, you can use a DataView to convert that to a timeofday data type:
var timeFormatter = new google.visualization.DateFormat('HH:mm:ss.SSS'); // set this pattern however you need to format your time display
var view = new google.visualization.DataView(data);
view.setColumns([/* columns before timeofday */, {
type: 'timeofday',
label: 'Time of Day',
calc: function (dt, row) {
var timeOfDay = toTimeSpan(data.getValue(row, /* time column index */);
var formattedTime = timeFormatter.formatValue(timeOfDay);
return {v: timeOfDay, f: formattedTime};
}
}, /* columns after timeofday */]);
0
On
Using as asgallant answer, that expanded the answer from Kenny Dewhirst I ended up doing something very similar but instead of using the function toTimeStamp, I used the new Date(milliseconds). Code below using livescript.
function millisToDate dt, row
date = new Date(dt.getValue(row, 0))
dateFormatter = new google.visualization.DateFormat({pattern: "EEEE d 'de' MMMM 'de' yyyy, H:mm"});
{v: date, f: dateFormatter.formatValue date}
view = new google.visualization.DataView data
view.setColumns([/* columns before timeofday */, {
type: 'datetime',
calc: millisToDate
}, /* columns after timeofday */])
NOTE: Using type: 'date' made that the horizontal axis did not displayed the hours in case the graph show one day data. Changing to datetime fixed this.
In Google Charts, a time span can be represented using the
timeofdaytype, which will allow you to add two times and get a third, and make charts automatically format things properly. Atimeofdayis actually an array with four elements: hours, minutes, seconds, and (optionally) milliseconds. See this page's explanation of thetimeofdayunder thetypeproperty for a DataTable'scols.Each field of the
timeofdayhas 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:A caveat: I don't think a
timeofdaywill allow you to hold a span greater than 24 hours. If you need that functionality, you may need to use anumbercolumn and write your own formatting.