[Chartjs]-Chartjs: Moment and ChartJS Time Format Parsing

1👍

When using time axis, no need to parse the dates yourself. Simply define time.parser and let Chart.js do it’s job. According to 3.x Migration Guide, a few other things need also to be changed to make it work with Chart.js v3.

Please take a look at your amended and runnable code below and see how it works.

<!DOCTYPE html>
<html>

<body>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.js">
  </script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-adapter-moment/1.0.0/chartjs-adapter-moment.min.js"></script>

  <div id="chartTarget" style="height: 160px; width: 100%;">
    <canvas id="deviceOnChart" width="600" height="160" style="display: block; height: 160px; width: 600px;"></canvas>
    <div style="opacity:0;" class="chartTooltip center">
    </div>
  </div>

</body>

</html>
<script>
  var temp = '{ "EmpLst": {"0" : "Parado","1" : "A pé"},"dateData" : [{"x": "07:00:00", "y": "09:10:00"},{"x": "08:00:00", "y": "08:10:00"}]}';

  var parsedJSon = JSON.parse(temp);
  var empNames = Object.values(parsedJSon.EmpLst);
  var dateData = Object.values(parsedJSon.dateData).map(o => [o.x, o.y]);

  var dataSets = [{
    label: 'data',
    data: dateData,
    backgroundColor: 'lightblue'
  }];

  var data = {
    type: 'bar',
    data: {
      labels: empNames,
      datasets: dataSets
    },
    options: {
      indexAxis: 'y',
      responsive: true,
      plugins: {
        title: {
          display: true,
          text: 'Horizontal Floating Bars'
        },
        tooltip: {
          callbacks: {
            label: ctx => {
              const v = ctx.dataset.data[ctx.dataIndex];
              return v[0] + ' - ' + v[1];           
            }
          }
        }
      },
      scales: {
        x: {
          type: 'time',
          time: {
            parser: 'h:mm:ss',
            unit: 'hour',
            displayFormats: {
              hour: 'HH:mm:ss'
            }
          },
          min: '00:00:00',
          max: '24:00:00'
        }
      }
    }
  };


  var chart = new Chart('deviceOnChart', data);
</script>

Leave a comment