Chartjs-Chart.js v2 formatting time labels

0👍

From the Chart.js time axis documentation:

When building its ticks, it will automatically calculate the most comfortable unit base on the size of the scale.

This appears to work well as shown in the two charts below, the first with a range of 10 minutes and the second with a range of 10 days:

let now = (new Date()).getTime(),
  minutes = [],
  days = [],
  options = {
    scales: {
      xAxes: [{
        type: 'time'
      }]
    }
  };

for (let i = 0; i < 10; i++) {
  minutes.push({
    x: now + (60000 * i),
    y: 10
  });
  days.push({
    x: now + (86400000 * i),
    y: 10
  });
}

new Chart(document.getElementById('canvas1'), {
  type: 'line',
  data: {
    datasets: [{
      data: minutes
    }]
  },
  options: options
});

new Chart(document.getElementById('canvas2'), {
  type: 'line',
  data: {
    datasets: [{
      data: days
    }]
  },
  options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js"></script>
<canvas id="canvas1"></canvas>
<canvas id="canvas2"></canvas>

You can pass in display formats for the various units (minute, day, month, etc) to automatically get the scaling and formatting you want.

Leave a comment