Home > Mobile >  Checking for date isWeekend for array of dates - Javascript
Checking for date isWeekend for array of dates - Javascript

Time:09-26

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)",
      },
    ],
  };

CodePudding user response:

Your isWeekend function is good, you 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

CodePudding user response:

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]));
}

  • Related