Reputation: 709
I am returning a JSON to my view and I want to parse the date on a line graph, but I am having some issues with adding dates using ChartJS.
This is my JSON format: (can be changed)
[
{ "y": 4, "x": "2017-01-01" },
{ "y": 0, "x": "2017-01-02" },
{ "y": 9, "x": "2017-01-03" },
{ "y": 0, "x": "2017-01-04" },
{ "y": 14, "x": "2017-01-05" }
]
I tried this but keep getting random timestamps
data: {
labels: [],
datasets: [{
data: [{
y: 0,
x: new Date('2017,03,01')
}, {
y: 1,
x: new Date('2017,03,02')
}, {
y: 2,
x: new Date('2017,03,03')
}],
label: "test",
Does anyone have any idea on how to put the correct dates on the x-axis and place the values on the y-axis? Thanks.
Upvotes: 0
Views: 3659
Reputation: 109
Use the json data as is, but tell chart.js that the x axis is time. working fiddle
options: {
"scales": {
"xAxes": [{
"type": "time"
}]
}
}
See http://www.chartjs.org/docs/latest/axes/cartesian/time.html for more time axis configuration options. Especially the parser (tick) property, if using various time and date formats.
Upvotes: 0
Reputation: 515
There is an error in Date initialization:
new Date('2017,03,01')
should be replaced by
new Date(2017,03,01)
(without quotes), because '2017,03,01' is a string with an invalid date format. You can initialize a Date object with a string with the following format (the same you have as input):
new Date('2017-03-01')
In order to trasform the json of your input you can write a function like this:
var input = [{"y":4,"x":"2017-01-01"},
{"y":0,"x":"2017-01-02"},
{"y":9,"x":"2017-01-03"},
{"y":0,"x":"2017-01-04"},
{"y":14,"x":"2017-01-05"}];
var data = input.map(function(item) {
return {x: new Date(item["x"]), y: item["y"]};
});
and pass data to your graph.
Upvotes: 2