JED
JED

Reputation: 1694

Chart.JS format date in label

How do you format the date in a datapoint's label in Chart.JS?

I've tried this:

this.chart = new Chart(ctx,
  {
    data: {
      labels: timestamps 
                .map(t => t.toLocaleString([], { month: '2-digit', day: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit' })),
      datasets: [
        {
          data: measurements
        }, 
        //etc...
]}});

It works, but I get a Moment.JS warning message:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format... Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release.

Is there a proper way to format dates for data labels in Chart.JS since the method I am using is apparently discouraged?

With labels: timestamps

chart showing default date format

With labels: timestamps.map(t => t.toLocaleString(...)

chart showing localeString format

Upvotes: 2

Views: 39830

Answers (1)

JED
JED

Reputation: 1694

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

Upvotes: 26

Related Questions