Chartjs-How can I format the x-axis using a timestamp via chart.js?

4👍

First, you must not define data.labels.

Further, the x-axis could be defined as follows:

x: {
  type: 'time',
  time: {
    unit: 'minute',
    displayFormats: {
      minute: 'DD T'
    },
    tooltipFormat: 'DD T'
  },
  ...

Please take a look at your amended and runnable code below and see how it works.

new Chart('canvas', {
  type: 'line',
  data: {
    datasets: [{
      label: 'Temperature',
      data: [
        {"x": 1647281788963, "y": 22.9}, 
        {"x": 1647281994496, "y": 26.9}, 
        {"x": 1647282200029, "y": 21.9}, 
        {"x": 1647282405562, "y": 24.9}, 
        {"x": 1647282611094, "y": 28.9}
      ],               
      backgroundColor: 'transparent',
      borderColor: 'red',
      borderWidth: 2,
      tension: 0.5
    }]
  },
  options: {
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'minute',
          displayFormats: {
              minute: 'DD T'
          },
          tooltipFormat: 'DD T'
        },
        title: {
          display: true,
          text: 'Date'
        }
      },
      y: {
        title: {
          display: true,
          text: 'value'
        }
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>
<canvas id="canvas" height="120"></canvas>

Leave a comment