Reputation: 321
I am trying to plot an array of values on a line plot. The values each have a date/time stamp. So an example data point is:
aPoint = { 'label': 201401082015, //so this corresponds to 2014, Jan 08th, at 10:15PM
'data' : 1234
};
How do I convert label
into a form that nvd3 can recognise as a date/time? By not changing the form of label
, incorrect spacing between data points will occur (due to 60 minutes in 1 hour, 24 hours in 1 day and not 100).
To elaborate, if an event occurs at 23:00
hrs (11pm), and another at 01:00
hrs (1am) the following day, then in reality these events are 2 hours apart. Incorrectly however, they will be plotted as if they are 78 hours (101-23=78) apart due to hours in a day not being base 10
.
How do I convert label
into a form that nvd3 can recognise as a date/time?
Upvotes: 0
Views: 74
Reputation: 13071
How do I convert label into a form that nvd3 can recognize as a date/time?
Like this:
function labelToMs(label){
var parts = label.toString().match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})$/);
var partsToInt = parts.slice(0,5).map(function(s){return parseInt(s)});
var date = new Date(partsToInt[0], partsToInt[1]-1, partsToInt[2], partsToInt[3], partsToInt[4]);
return date.getTime();
}
This function will return a number that won't have that issue, because it will be the number of milliseconds since 1 January 1970 00:00:00 UTC.
Also, if you have an Array of points and you want to convert it to an Array with the label as the number of MS, you could do it like this:
var yourArrayOfPoints = yourArrayOfPoints.map(function(point){
point.label = labelToMs(point.label);
return point;
});
Upvotes: 1