Chartjs-Chart.js – Format Date on X-Axis

1👍

The answer is that I needed to use chart.bundle.js which apparently included moment.js, which helps with date/time parsing.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script> 

I found this from ChartJS – format datetime X axis when displaying data from MySql table

The suggested post (comment to original question) then allowed me to control the formatting more precisely.

So I ended up with

enter image description here

scales: {
   xAxes: [{
      type: 'time',
      time: {
        unit: 'hour',
        displayFormats: {
           'hour': 'HH:MM',
        }
      }
   }],
},  // end scales      

I could only find chart.bundle.js up to version 2.9.3 so I did try including chart.js and moment.js separately but could not get that to work. I will spend some more time on that problem, so that I can use later versions of chart.js. Although, moment.js appears to be "end-of-project" so I am not sure if there is an alternative and how that would work with chart.js – but that’s a different problem

Thanks for the help

Update: Here’s the chart.js v4.1.1 solution

<script src="https://cdn.jsdelivr.net/npm/chart.js@^4"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

And the scales configuration:

    scales: {
       x: {
          type: 'time',
          time: {
            unit: 'hour',
            displayFormats: {
               'hour': 'HH:MM',
            }
          }
       },
    },  // end scales         

Leave a comment