[Chartjs]-How to set the xAxes min and max values of time cartesian chart in Chart.js

2👍

You are trying to use v2 and v3 config at the same time, this wont work. You need to remove the array format and only use the objects to define scales.

When placing the min and max props at the root of the x object for the x scale it works fine, although the time between the min and max you are using is only 1,5 minute:

// setup block
const data = {
  datasets: [{
    label: 'Sales',
    data: [{
        x: '2021-08-08T13:12:23',
        y: 3
      },
      {
        x: '2021-08-08T13:12:45',
        y: 5
      },
      {
        x: '2021-08-08T13:12:46',
        y: 6
      },
      {
        x: '2021-08-08T13:13:11',
        y: 3
      },
      {
        x: '2021-08-08T13:14:23',
        y: 9
      },
      {
        x: '2021-08-08T13:16:45',
        y: 1
      }
    ],
    borderColor: 'rgba(234,124,234,0.4)',
    backgroundColor: 'rgba(34,14,24,0.4)'
  }]
};
// config block
const config = {
  type: 'line',
  data,
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'second'
        },
        min: '2021-08-08T00:00:00',
        max: '2021-08-08T23:59:59'
      },
      y: {
        beginAtZero: true
      }
    }
  }
};
// render / init block
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="main.css">
</head>

<body>
  <div class="chart-container">
    <canvas id="myChart"></canvas>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
  <script src="my-chart.js"></script>
</body>

</html>

Leave a comment