[Chartjs]-How to plot chart from external JSON and format X-AXIS to show time using Chart.JS?

2👍

You can use a time axis:

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/moment@^2"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@^1"></script>
</body>

or you can use a custom tick callback to achieve this

const options = {
  type: 'line',
  data: {
    labels: ["Fri Feb 11 2022 00:59:07 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:17 GMT+0530 (Indian Standard Time)", "Fri Feb 11 2022 00:59:27 GMT+0530 (Indian Standard Time)"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
    }]
  },
  options: {
    scales: {
      x: {
        ticks: {
          callback: function(val) {
            return this.getLabelForValue(val).substring(16, 24);
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
</body>

Documentation: https://www.chartjs.org/docs/master/axes/labelling.html#creating-custom-tick-formats

Leave a comment