How to change format of datetime reading into chart.js chart?

by ryan.murray , in category: Javascript , 10 months ago

How to change format of datetime reading into chart.js chart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by aubrey , 10 months ago

@ryan.murray 

To change the format of datetime readings in a Chart.js chart, you can use moment.js, a popular JavaScript library for parsing, validating, manipulating, and formatting dates and times. Here's how you can modify the datetime format in your chart:

  1. Include moment.js library in your HTML file:
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


  1. Assuming you have a line chart as an example, you can format the datetime in the chart data like this:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['2022-01-01T00:00:00Z', '2022-01-02T00:00:00Z', '2022-01-03T00:00:00Z'],
        datasets: [{
            label: 'My Data',
            data: [10, 20, 30]
        }]
    },
    options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    parser: 'YYYY-MM-DDTHH:mm:ssZ',
                    tooltipFormat: 'll'
                }
            }]
        }
    }
});


In this example, the parser option specifies the format in which the datetime strings in the labels array will be parsed. The tooltipFormat option specifies the format in which the tooltips will display the datetime values.


You can use moment.js format tokens to specify the desired datetime format. More information on moment.js format tokens can be found in the moment.js documentation: https://momentjs.com/docs/#/displaying/format/


By using moment.js and specifying the datetime format in the chart options, you can easily customize the datetime format in your Chart.js chart.