Reputation: 9800
As you can see in the example below, my dates are starting at 2022-11-24, however in chart it starts from 2022-11-23, and all rest of dates get shifted by about a day. What's causing this issue ? Thanks !
let chart_dates = ['2022-11-24T00:00:00Z', '2022-11-25T00:00:00Z', '2022-11-26T00:00:00Z', '2022-11-27T00:00:00Z', '2022-11-28T00:00:00Z', '2022-11-29T00:00:00Z', '2022-11-30T00:00:00Z'];
let chartDataSet = [{"label":"A","data":[0,23,0,0,25,31,2],"lineTension":0.2,"borderColor":"#4e73df"},{"label":"B","data":[0,1,0,0,18,6,0],"lineTension":0.2,"borderColor":"#1cc88a"}];
new Chart(document.getElementById("chartJSContainer"), {
type: 'line',
data: {
labels: chart_dates,
datasets: chartDataSet
},
options:{
scales: {
x: {
type: 'time',
time: {
unit: 'day'
}
}
}
}
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</body>
Upvotes: 1
Views: 187
Reputation: 14870
The issue occurs due to the timeoffset of localtime to Zulu/UTC Time. Your timezone has (probably) a negative offset, that why it seems off for some hours.
My time offset is positive (+02:00),so it looks fine for me (chart begins at 24.11 more or less). Just use localtime datetimes in your data than you should not have this issue anymore.(Or just remove the time part if you don't need/use it -> '2022-11-24')
Just for demo I remove the (Zulu) Z
in the date dataset, to show case this:
(Due to this change, the Datetime items are now interpreted as localtime)
let chart_dates = [
'2022-11-24T00:00:00', '2022-11-25T00:00:00', '2022-11-26T00:00:00',
'2022-11-27T00:00:00', '2022-11-28T00:00:00', '2022-11-29T00:00:00',
'2022-11-30T00:00:00', ];
let chartDataSet = [
{"label":"A","data":[0,23,0,0,25,31,2],"lineTension":0.2,"borderColor":"#4e73df"},
{"label":"B","data":[0,1,0,0,18,6,0],"lineTension":0.2,"borderColor":"#1cc88a"},
];
new Chart(document.getElementById("chartJSContainer"), {
type: 'line',
data: {
labels: chart_dates,
datasets: chartDataSet
},
options:{
maintainAspectRatio: false,
scales: {
x: {
type: 'time',
time: {
unit: 'day'
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
<div class="chart" style="height:184px;width:500px">
<canvas id="chartJSContainer" width="600" height="400"></canvas>
</div>
Upvotes: 1