[Chartjs]-Formatting x-axis labels as time values in Chart.js

2👍

All you need is to define your xAxis as a time cartesian axis with a ‘day’ unit.

The default display format of ‘day’ is ‘MMM D’ (for instance ‘Feb 2’).

options: {
    ...
    scales: {
        xAxes: [{
            type: 'time',
            time: {
                unit: 'day',
                tooltipFormat: 'MMM DD' 
            }
            ...
        }]
    }
    ... 
}

Please have a look at the following runnable code snippet:

new Chart(document.getElementById('myChart'), {
  type: 'line',  
  data: {
    labels: ['2020-02-06', '2020-02-07', '2020-02-08', '2020-02-09', '2020-02-10', '2020-02-11', '2020-02-12'],
    datasets: [{
      label: 'My Dataset',
      data: [0.758, 0.756, 0.755, 0.754, 0.753, 0.758, 0.76],
      fill: false,
      backgroundColor: 'green',
      borderColor: 'green'
    }]
  },
  options: {
    responsive: true,
    title: {
      display: false
    },
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          min: .74,
          max: .76,
          stepSize: .005
        }
      }],
      xAxes: [{
        type: 'time',
        time: {
          unit: 'day',
          tooltipFormat: 'MMM DD'
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Leave a comment