Search code examples
javascriptreact-chartjs-2

Checking for date isWeekend for array of dates - Javascript


I would like to check which days are weekends in my array. For now I only managed to check on single dates, and not the whole array at once.

If it is a weekend I would like to change the color on my barchart. Any help would be much appreciated.

const dates = ['2022-07-15', '2022-07-16', '2022-07-17', '2022-07-18', '2022-07-19', '2022-07-20']

function isWeekend(date = new Date()) {
    return date.getDay() === 6 || date.getDay() === 0;
  }

  const d1 = new Date(dates);

  console.log(d1.getDay()); 

  console.log(d1.isWeekend()); 

  const data = {
    labels: dates,
    datasets: [
      {
        label: "Amount of Visitors",
        data: [1, 4, 3, 7, 5, 2],
        backgroundColor: "rgba(255, 99, 132, 0.5)",
      },
    ],
  };

Solution

  • Your isWeekend function looks good (ignoring time zone support), you likely just need to set the background colors in your bar chart:

    const data = {
      labels: dates,
      datasets: [
        {
          label: 'Amount of Visitors',
          data: [1, 4, 3, 7, 5, 2],
          backgroundColor({ dataIndex }) {
            return isWeekend(new Date(dates[dataIndex])) ? 'green' : 'red';
          },
        },
      ],
    };
    

    https://codesandbox.io/s/check-for-dates-on-weekends-dv07np?file=/src/Visitors.js