ChartJS to Use time for xAxes - Javascript Chart.js

Javascript examples for Chart.js:Axis

Description

ChartJS to Use time for xAxes

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//  ww w  .  ja va 2s.  co m
$(document).ready(function() {
   new Chart(document.getElementById("chartBox"), {
      type: 'line',
      data: {
         datasets: [{
            data: [12, 19, 3, 5, 2, 3, 32, 15],
            label: "",
            borderWidth: 2,
            borderColor: "#3e95cd",
            fill: false,
            pointRadius: 0
         }]
      },
      options: {
         scales: {
            xAxes: [{
               type: 'time',
               time: {
                  parser: 'YYYY-MM-DD HH:mm:ss',
                  unit: 'day',
                  displayFormats: {
                     day: 'ddd'
                  },
                  min: '2017-10-02 18:43:53',
                  max: '2017-10-09 18:43:53'
               },
               ticks: {
                  source: 'data'
               }
            }]
         },
         legend: {
            display: false
         },
         animation: {
            duration: 0,
         },
         hover: {
            animationDuration: 0,
         },
         responsiveAnimationDuration: 0
      },
      plugins: [{
         beforeInit: function(chart) {
            var time = chart.options.scales.xAxes[0].time, // 'time' object reference
            timeDiff = moment(time.max).diff(moment(time.min), 'd'); // difference (in days) between min and max date
            for (i = 0; i <= timeDiff; i++) {
               var _label = moment(time.min).add(i, 'd').format('YYYY-MM-DD HH:mm:ss');
               chart.data.labels.push(_label);
            }
         }
      }]
   });
});
    }

      </script> 
   </head> 
   <body> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 
      <script src="https://cdn.jsdelivr.net/npm/moment@latest/moment.min.js"></script> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script> 
      <canvas id="chartBox"></canvas>  
   </body>
</html>

Related Tutorials