1

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)",
      },
    ],
  };
Sindawg
  • 13
  • 2
  • Similar in this [post](https://stackoverflow.com/questions/46657889/get-weekend-using-moment) – Creek Sep 26 '22 at 10:01
  • Moment is in legacy mode so I wouldn't recommend it. `getDay()` is fine. – Nick McCurdy Sep 26 '22 at 10:03
  • The problem that I am having with the ```getDay()``` is that I can only get it to take 1 value, is there any way to check the whole array at once? Or should is it better just to loop through the array? – Sindawg Sep 26 '22 at 10:14
  • Just loop through the array – Arijit Sep 26 '22 at 10:26

2 Answers2

0

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

Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82
0

const dates = ['2022-07-15', '2022-07-16', '2022-07-17', '2022-07-18', '2022-07-19', '2022-07-20'];
function isWeekEnd(date){
  var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  var day = new Date(date);
  var dayName = days[day.getDay()];
  console.log(dayName);
  switch (dayName) {
    case 'Friday':
      return true
      break;
    case "Saturday":
      return true
      break;
    default:
      return false
  }
}
for(var i=0;i<dates.length;i++){
  console.log(isWeekEnd(dates[i]));
}
Mohammad
  • 36
  • 3