[Chartjs]-Dump missing date in data for chartjs

9👍

This can be done outside of the actual graph by pre-parsing you labels to check that they are sequential in date. In the example below i have made use of momentjs as it just makes date manipulation, formatting and parsing so much easier.

then it is just a case of when finding a date that is not followed by a squential date to add it in to the labels and also the graph data.

var graphData = [55, 10, 5],
  labels = ["01-11-2014", "04-11-2014", "05-11-2014"];


for (var i = 0; i < labels.length; i++) {
  //make sure we are not checking the last date in the labels array
  if (i + 1 < labels.length) {
    var date1 = moment(labels[i], "DD-MM-YYYY");
    var date2 = moment(labels[i + 1], "DD-MM-YYYY");

    
    //if the current date +1 is not the same as it's next neighbor we have to add in a new one
    if (!date1.add(1, "days").isSame(date2)) {
      
      //add the label
      labels.splice(i + 1, 0, date1.format("DD-MM-YYYY"));
      //add the data
      graphData.splice(i + 1, 0, 0);
    }
  }


}


var ctx = document.getElementById("chart").getContext("2d");
var data = {
    labels:labels,
    datasets: [{
        label: "My First dataset",
        fillColor: "rgba(220,220,220,0.5)",
        strokeColor: "rgba(220,220,220,0.8)",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",

        data: graphData
    }]
};


var myLineChart = new Chart(ctx).Line(data);

console.log(labels);
console.log(graphData);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
<script src="https://raw.githack.com/leighquince/Chart.js/master/Chart.min.js"></script>
<canvas id="chart" width="500px"></canvas>

Leave a comment