Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find weekends inside a date array in javascript

I have a date array, what I want is to do two things with it.

1.- Tell me how many dates within it are weekends
2.- Create a new arrangement with the dates that are weekends

I tried the following code but I don’t know how to return when the weekend is true, as you can see the code only evaluates when getDay is 0 (Sunday) and 6 (Saturday), I would have to find a way to put those that are true inside the array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const whenIsWeekend = [];
attendanceDates.forEach(element => {

  const date = new Date(element)
  var dayOfWeek = date.getUTCDay();
  var isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0); // 6 = Saturday, 0 = Sunday
  console.log('isWeekend', isWeekend);
  if (isWeekend) {
    whenIsWeekend.push(element)
  }
})


console.log('array of Weekend', whenIsWeekend)

console.log('count weekends', whenIsWeekend.length)

What I hope to return

array of Weekend [
   "2022-11-26"
]
count weekends 1

Thank your in advance

>Solution :

Using the native Javascript date object:

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const weekends = attendanceDates.filter(date => {
    const dateObj = new Date(date)
    const dayOfWeek = dateObj.getUTCDay();

    if (dayOfWeek == 0 || dayOfWeek == 6) {
        return true;
    }
})

console.log(weekends) //["2022-11-26"]

Using moment.js library (ideal if you need to do many date manipulations easily)

const attendanceDates = [
  "2022-11-21",
  "2022-11-22",
  "2022-11-24",
  "2022-11-26"
]

const weekends = attendanceDates.filter(date => {
    const dateMoment = moment(date)
    if (dateMoment.day() == 0 || dateMoment.day() == 6) {
        return true;
    }
})

console.log(weekends) //["2022-11-26"]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading