[Chartjs]-Chart.js time series

1👍

Welcome to the world of coding. Never mind asking questions – it’s professional, and we all started one day 🙂

I hope I understood correctly your need and offer a solution right away with latest version:

Chart.js v3.xx (not compatible with v2.xx)

Time Series Axis (with moment.js + adapter):

Source: https://www.chartjs.org/docs/latest/axes/cartesian/timeseries.html

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
   //gets you the latest version of chart, now v3.2.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/chartjs-adapter-moment"></script>
   //you need this adapter for timeseries to work with momentjs 

<div>
  <canvas id="timeSeriesChart"></canvas>
</div>

<script>
Chart.defaults.font.family = 'Poppins';
   // watch out, it's not Chart.defaults.global.defaultFontFamily anymore as in v2.xx

const ctx = document.getElementById('timeSeriesChart').getContext('2d');

const startDate = new Date(2020, 10, 30);
const labels = [];

let i = 0;
   //tip: declare variable `i` outside `for ()` loop - better performance
let date = new Date();
   //also: declare variable `date` outside `for ()` loop

for (i; i < 13; i++) {
  date = moment(startDate).add(i, 'weeks').format('YYYY/MM/DD');  
    //add `weeks` instead of `days` if you have weekly totals
    //add `days` if you have daily totals

  labels.push(date.toString());
}

const chart = new Chart(ctx, {
  type: 'line',
  data: {
    labels,
    datasets: [{
      label: 'Recruitment Candidates',
      data: [4, 5, 6, 90, 56, 32, 14, 6, 72, 99],
      borderWidth: 1,
      tension: 0.3,
      fill: true
    }]
  },
  options: {
    scales: {   //watch out here - new syntax in v3.xx
      x: {
        type: 'timeseries',
        time: {
            unit: 'week',  //this does the trick :-)
            isoWeekday: true,
                // declare Monday as the first day of the week
                // because in some locale, sunday would be first day of week
        }
      }
    }
  }
});

</script>

You should get following result:
Recruitment per week Chart

Hope this helps and happy coding …

Leave a comment