[Chartjs]-Chart.JS format date in label

26πŸ‘

βœ…

I was able to find the answer by inspecting the source HTML file of a sample chart provided by Chart.js.

In order to format the dates properly, one must add the parser and tooltipFormat properties to the axis in question. To fix my example given above:

this.chart = new Chart(ctx,
  {
    type: 'line',
    data: {
      labels: timestamps,
      datasets: [
        {
          data: measurements,
        }
      ]
    },
    options: {
      scales: {
        xAxes: [ {
            display: true,
            type: 'time',
            time: {
              parser: 'MM/DD/YYYY HH:mm',
              tooltipFormat: 'll HH:mm',
              unit: 'day',
              unitStepSize: 1,
              displayFormats: {
                'day': 'MM/DD/YYYY'
              }
            }
          }
        ],
        yAxis: [
          // etc...
        ],
      }
    }
  }
);

EDIT (1/17/2023)

The sample chart that I linked initially has been removed from the Chart.js documentation. Here’s their latest link regarding time scales: Time Cartesian Axis | Chart.js

Leave a comment