[Chartjs]-Working with multiple date axes in ChartJS

1👍

The issue you are getting is because of 2 things. The first thing is that you are not using the date adapter your say you are using. You are using another one and importing it with skypack which has the big side effect of also import Chart.js itself. The version of Chart.js that skypack imports is version 2.

The lib that you are linking does not seem to have a build available that works out of the blue in your browser even with their example using script tags. So if you want to use day.js you will need to write your own date adapter.

Example of just using js dates and using the date-fns date adapter:

let start = new Date(),
  end = new Date();
start.setDate(start.getDate() - 7); // set to 'now' minus 7 days.
start.setHours(0, 0, 0, 0); // set to midnight.

new Chart(document.getElementById("lastSevenDaysOverview"), {
  type: "line",
  data: {
    datasets: [{
        label: 'Dataset 1',
        data: [{
          x: new Date('10-16-2021'),
          y: 1
        }, {
          x: new Date('10-18-2021'),
          y: 4
        }, {
          x: new Date('10-19-2021'),
          y: 66
        }],
        borderColor: '#ff3366',
        backgroundColor: '#ff3366',
      },
      {
        label: 'Dataset 2',
        data: [{
          x: new Date('10-16-2021'),
          y: 31
        }, {
          x: new Date('10-18-2021'),
          y: 14
        }, {
          x: new Date('10-19-2021'),
          y: 6
        }],
        borderColor: '#880000',
        backgroundColor: '#880000'
      }
    ]
  },
  options: {
    interaction: {
      mode: 'index',
      intersect: true,
    },
    responsive: true,
    scales: {
      y: {
        type: 'linear',
        display: true,
        position: 'left',
      },
      x: {
        type: "time",
        time: {
          unit: "day"
        }
      }
    },
  }
});
<canvas id="lastSevenDaysOverview"></canvas>
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

Leave a comment