Reputation: 65
I have dates stored in an array that needs to be display on the x-axis of the chart. How can I format the date so that it renders properly on x-axis?
{
"xData": ["2020-10-01T19:30:00.000Z",
"2020-10-02T19:30:00.000Z",
"2020-10-03T19:30:00.000Z",
"2020-10-04T19:30:00.000Z",
"2020-10-05T19:30:00.000Z",
...
...
]
}
Highcharts.chart('container, {
chart: {
marginLeft: 40
},
title: {
text: ''
},
xAxis: {
categories: Date.UTC(xData),
},
yAxis: {
title: {
text: null
}
},
series: [{
data: dataset.data,
}]
});
Upvotes: 5
Views: 9616
Reputation: 39139
If you want to use x-axis with categories, map your date strings to an array with strings with the format you want.
xAxis: {
categories: dataset.xData.map(date => {
return Highcharts.dateFormat('%Y-%m-%d', new Date(date).getTime());
})
}
Live demo: http://jsfiddle.net/BlackLabel/oL1ncjes/
API Reference: https://api.highcharts.com/class-reference/Highcharts#.dateFormat
But I think that a more suitable solution would be to create data in [x, y]
format, use datetime x-axis type and labels format:
const processedData = dataset.data.map((dataEl, i) => {
return [new Date(dataset.xData[i]).getTime(), dataEl] // x, y format
});
Highcharts.chart('container', {
...,
xAxis: {
type: 'datetime',
labels: {
format: '{value:%Y-%m-%d}'
}
},
series: [{
data: processedData
}]
});
Live demo: http://jsfiddle.net/BlackLabel/y0dkzn1q/
API Reference: https://api.highcharts.com/highcharts/xAxis.type
Upvotes: 12