[Chartjs]-How to parse "hh:mm:ss" strings to time in Charts.js 3.x

4πŸ‘

βœ…

In chart.js v3 they removed moment and the adapter so you will need to add both to your script and it should work

Example:

var ctx = document.getElementById('chart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        datasets: [
            {
            label: "Switched",
            data: [{x:"00:00:07", y: 0}, {x:"00:00:14", y: 0}, {x:"00:05:24", y: 0}],
            showLine: false,
            fill: false,
            tooltip: "Player switched",
            borderColor: "#16a085",
            backgroundColor: "#16a085"
        }
    ]},
    options: {
        responsive: true,
        scales: {
        x: {
                type: 'time',
                time: {
                    parser: 'HH:mm:ss',
                    unit: "seconds",
                    tooltipFormat: 'HH:mm:ss',
                    displayFormats: {
                        'seconds': "HH:mm:ss"
                    },
                    unitStepSize: 30
                }
            },
            y: {
                min: -1,
                max: 13,
                stepSize: 1,
            }
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment@0.1.1"></script>

<canvas id="chart" height= "80px" style="background-color: rgb(50, 50, 50);"></canvas>

Leave a comment