1👍
✅
The problem is located in your formatData
function. Using moment
, you correctly parse the time but then you format
it back to its original string
value. The solution is to no longer call format
.
currentData.x = moment(oldData[i].x, "HH:mm");
And the whole thing:
var sData = {
datasets: [{
label: 'Dataset1',
data: [{ x: '09:00', y: 88 }, { x: '09:10', y: 89 }, { x: '09:13', y: 86 }, { x: '09:23', y: 86 },
{ x: '09:26', y: 85}, { x: '09:29', y: 83 }]
}, {
label: 'Dataset2',
data: [{ x: '09:02', y: 88 }, { x: '09:13', y: 89 }, { x: '09:14', y: 86 }, { x: '09:20', y: 86 },
{ x: '09:24', y: 85 }, { x: '09:29', y: 83 }]
}]
}
sData.datasets[0].data = formatData(sData.datasets[0].data)
sData.datasets[1].data = formatData(sData.datasets[1].data)
function formatData(oldData) {
var newData = []
for (var i = 0; i < oldData.length; i++) {
var currentData = {}
currentData.x = moment(oldData[i].x, "HH:mm")
currentData.y = oldData[i].y
newData.push(currentData)
}
return newData
}
var options = {
responsive: true,
scales: {
xAxes: [{
type: 'time',
}]
},
tooltips: {
callbacks: {
title: (tooltipItem, data) => moment(tooltipItem[0].label).format('HH:mm')
}
}
}
var ctx = document.getElementById('bateria_graf').getContext('2d');
let chart = new Chart(ctx, {
type: 'line',
data: sData,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.1.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="bateria_graf"></canvas>
Source:stackexchange.com