[Chartjs]-Chartjs not displaying timed data

2👍

In my opinion your code looks good and should work. Semantically, however, the use of the timeline is not quite correct. Your bars actually represent durations.

Please have a look at your amended code that works now with durations instead of times:

function asSeconds(value) {
  const tokens = value.split(':');
  return Number(tokens[0]) * 60 + Number(tokens[1]);
}

function format(seconds) {
  return moment.utc(seconds * 1000).format("mm:ss");
}

new Chart('canvas', {
  type: 'horizontalBar',
  data: {
    labels: ['labelA', 'labelB'],
    datasets: [{
      label: 'My Dataset',
      data: ['10:32', '00:12'].map(v => asSeconds(v)),
      backgroundColor: ['red', 'blue'],
      borderWidth: 1
    }]
  },
  options: {
    responsive: 'true',
    scales: {
      xAxes: [{
        ticks: {
          min: 0,
          stepSize: 60,
          max: asSeconds('20:00'),
          callback: s => format(s)
        }
      }]
    },
    tooltips: {
      callbacks: {
        label: (tooltipItem, data) => format(data.datasets[0].data[tooltipItem.index])
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="80"></canvas>

Leave a comment