[Chartjs]-Get last 6 month name in Array for Chartjs

2👍

Create an array having months , use getMonth() of date object to get present month and Array.slice() to extract last 6 months.

let months=["January","February","March","April","June", "July", "August", "September", "October", "November", "December"];
let currentMonth=new Date().getMonth()
var profitChart = {
        labels:months.slice(currentMonth-6).concat(months.slice(0,currentMonth)),
        datasets: [
          {
            label: "Profit",
            backgroundColor: "rgba(58,181,74,0.3)",
            borderColor: "rgba(58,181,74,0.80)",
            pointRadius: false,
            pointColor: "rgba(210, 214, 222, 1)",
        pointStrokeColor: "#c1c7d1",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: "profitdata",
      }]
      }
 console.log(profitChart)

0👍

If anyone needs the last n months, for any positive integer n you could do this:

const getLastNMonths = n => {           
        const d = new Date();
        const currentMonth = d.getMonth();
        const locale = 'en-GB';

        let result = [];
        for (let i = n; i > 0; i--) {
            d.setMonth(currentMonth - i);
            result.push(d.toLocaleDateString(locale, { month: 'long' }));
        }
        return result;
    };

In the OPs case they would need to use getLastNMonths(6) like this

var profitChart = {
    labels: getLastNMonths(6),
    //other properties
}

The benefit of this approach is that you can change the language by changing the locale parameter. Or leave it as undefined to output the months according to local timezone and default locale.

Leave a comment