[Chartjs]-How to display date as label on x-axis in chart.js

8👍

If I have understood you correctly then you just want the x-axis to be a date so 2018-12-07 15:45:17. I have managed to get that. Here is the entire code I have. Haven’t used chart.js before and haven’t got much time to look properly but look at the displayFormats and change how you want. Hope this helps.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.js"></script>

<body>
<canvas id="myChart" width="400" height="400"></canvas>

<script>
$(document).ready(function(){
        var time_Array = ["2018-12-07 15:45:17", "2018-12-07 15:30:17", "2018-12-07 15:15:16", "2018-12-07 15:00:17", "2018-12-07 14:45:16", "2018-12-07 14:30:17", "2018-12-07 14:15:17", "2018-12-07 14:00:17", "2018-12-07 13:45:17", "2018-12-07 13:30:16", "2018-12-07 13:15:17", "2018-12-07 16:00:17"];
        var meas_value_Array = [121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121, 121];


        //console.log(time_Array);
        //console.log(meas_value_Array);

        var ctx = document.getElementById ('myChart').getContext('2d');
        var myChart = new Chart(ctx, {
        type: 'line',
        data: {
        labels: time_Array,
        datasets: [{
        label: 'Humidity',
        data: meas_value_Array,
        backgroundColor: "rgba(255,153,0,0.4)"
        }]
        },

            options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }],
                xAxes: [{
                    type: 'time',
                    time: {
                        parser: 'YYYY-MM-DD HH:mm:ss',
                        unit: 'minute',
                        displayFormats: {
                            'minute': 'YYYY-MM-DD HH:mm:ss',
                            'hour': 'YYYY-MM-DD HH:mm:ss'
                        }
                    },
                    ticks: {
                        source: 'data'
                    }
                }]                    
            }
        }
    });
});
</script>

</body>
</html>

Leave a comment