1👍
So, after a bit of trying I’ve found a solution that could be tailored perfectly for you needs.
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: getPreviousMonths(),
},
options: {
responsive: true,
title: {
display: true,
text: 'Chiffre d\'affaire - année 2018'
},
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'month'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
}
}
});
function getPreviousMonths() {
var months = [];
months = Array.apply(0, Array(12)).map(function(_,i){return moment().month(i).toISOString()})
return months;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>
This is the same function you had but uses the function moment().month()
that returns an array of months and it formats it with the format you wanted. (It shows only half months in this snippet because it can’t extent through the entire page and cuts half months, should work on a full window)
I really don’t understand why your code was not working, I guess something happens when you reverse the order but anyway this should work. Cheers!
=== EDIT ===
As suggested in the comments, the formatting was removed and was added the function toISOString()
. This is because before, the date was getting transformed to a jsDate which is not supported by all browsers.