[Chartjs]-Chart.js time scale axis showing large numbers instead of dates

0👍

Assuming you are using the latest version of Chart.js, you will need to pass the correct configuration object so that it can render the dates as per the format provided. Can you please try something like this:

 const cfg = 
  {
    type: 'scatter',
    data: {
      datasets: [
        {
          labels: "Events",          
          data: args,
        }
      ]
    },
    options: {
      scales: {
        x: [ {
            display: true,
            type: 'time',
            time: {
              parser: 'MM/DD/YYYY HH:mm',
              tooltipFormat: 'll HH:mm',
              unit: 'day',
              unitStepSize: 1,
              displayFormats: {
                'day': 'MM/DD/YYYY'
              }
            }
          }
        ],
        y: [
          // etc...
        ],
      }
    }
  }
);

UPDATE

For older versions 2.x of Chart.js, the time scale requires both a date library and corresponding adapter to be present. By default, Chart.js includes an adapter for Moment.js. More info here.

Reference doc: Time Axis Specific Options

Hope that helps!

WORKING SOLUTION (Using Adapter)

Hello, I figured this out. In the last version 4.2.1 of Chartjs it is mentioned in the documentation that

Date Adapters
The time scale requires both a date library and a corresponding adapter to be present.

Hence you would need to modify your code as follows:

HTML

<canvas id="myCanvas"></canvas>

JavaScript

In addition to loading the Chart.js script, you would also need to load the corresponding adapter scripts date_fns.js and chartjs-adapter-date-fns-bundle.min.js

const options = {
  type: 'line',
  data: {
    datasets: [{
      label: '# of Entries',
      data: [{
        x: '2021-11-06 23:39:30',
        y: 5
      }, {
        x: '2008-04-12 13:30:14',
        y: 10
      }],
      borderColor: 'pink'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time'
      }
    }
  }
}

const ctx = document.getElementById('myCanvas').getContext('2d');
new Chart(ctx, options);

Here is the working fiddle for reference.

List of adapters can be found over here.

Leave a comment