Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Skip saturday and sunday looping in month

Tags:

javascript

I need to create an array of objects connected to each day of the month excluding weekends. example: Monday -1, Tuesday-2, Wednesday-3, Thursday-4, Friday-5, Monday-8 and so on. // jump two days

I found this snippet very useful for my idea...

code:

function getDaysArray(year, month) {
  var numDaysInMonth, daysInWeek, daysIndex, index, i, l, daysArray;

  numDaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  daysIndex = {
    'Sun': 0,
    'Mon': 1,
    'Tue': 2,
    'Wed': 3,
    'Thu': 4,
    'Fri': 5,
    'Sat': 6
  };
  index = daysIndex[(new Date(year, month - 1, 1)).toString().split(' ')[0]];
  daysArray = [];

  for (i = 0, l = numDaysInMonth[month - 1]; i < l; i++) {
    if (daysInWeek[index++] == "Sunday" || daysInWeek[index++] == "Saturday") {
      continue; //I tried: no success.
    }
    daysArray.push({
      "title": "Turn",
      "resourceid": "4",
      "start": year + "-" + month + "-" + (i + 1) + "+" + "08:00:00",
      "end": year + "-" + month + "-" + (i + 1) + "+" + "14:00:00",
      "internals": ground[i] // people from array to assign at specific date
    });

    if (index == 7) index = 0;
  }

  return daysArray;
}
console.log(getDaysArray(2019, 12));
like image 966
sundsx Avatar asked Dec 06 '25 03:12

sundsx


1 Answers

Easier: just use your index variable. If it equals 0 or 6, then it's a weekend, so don't push the day.

function getDaysArray(year, month) {
    var numDaysInMonth, daysInWeek, daysIndex, index, i, l, daysArray;

    numDaysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    daysInWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    daysIndex = { 'Sun': 0, 'Mon': 1, 'Tue': 2, 'Wed': 3, 'Thu': 4, 'Fri': 5, 'Sat': 6 };
    index = daysIndex[(new Date(year, month - 1, 1)).toString().split(' ')[0]];
    daysArray = [];

    for (i = 0, l = numDaysInMonth[month - 1]; i < l; i++) {
    	if (index != 0 && index != 6) {
           daysArray.push({
                "title":"Turn",
                "resourceid":"4",
                "start":year+"-"+month+"-"+(i + 1)+"+"+"08:00:00",
                "end":year+"-"+month+"-"+(i + 1)+"+"+"14:00:00"
            });
      }
      
      index++;

      if (index == 7) index = 0;
    }

    return daysArray;
}
    
console.log(getDaysArray(2019, 12));
like image 79
Francois Verollet Avatar answered Dec 07 '25 17:12

Francois Verollet