Skip to content

Instantly share code, notes, and snippets.

@NerdGr8
Forked from markthiessen/getWeeksInMonth.js
Created July 11, 2018 19:52
Show Gist options
  • Save NerdGr8/c322fe1c44b19ed3fa259012a4652dde to your computer and use it in GitHub Desktop.
Save NerdGr8/c322fe1c44b19ed3fa259012a4652dde to your computer and use it in GitHub Desktop.
JavaScript - get weeks in a month as array of start and end days
//note: month is 0 based, just like Dates in js
function getWeeksInMonth(month, year){
var weeks=[],
firstDate=new Date(year, month, 1),
lastDate=new Date(year, month+1, 0),
numDays= lastDate.getDate();
var start=1;
var end=7-firstDate.getDay();
while(start<=numDays){
weeks.push({start:start,end:end});
start = end + 1;
end = end + 7;
if(end>numDays)
end=numDays;
}
return weeks;
}
@NerdGr8
Copy link
Author

NerdGr8 commented Jul 11, 2018

function getWeeksStartAndEndInMonth(month, year, _start) {
    let monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"
        ],
        d = new Date();
    console.log("The current month is " + monthNames[d.getMonth()]);
    let weeks = [],
        firstDate = new Date(year, month, 1),
        lastDate = new Date(year, month + 1, 0),
        numDays = lastDate.getDate();
    var c = Date()
    let start = 1;
    let end = 7 - firstDate.getDay();
    if (_start == 'monday') {
        if (firstDate.getDay() === 0) {
            end = 1;
        } else {
            end = 7 - firstDate.getDay() + 1;
        }
    }
    while (start <= numDays) {
        var businessWeekEnd = end-2
        if(businessWeekEnd > 0){
            if(businessWeekEnd > start){
                weeks.push({start: start, end: businessWeekEnd});
            }
            else{
                //Check for last day else end date is within 5 days of the week.
                weeks.push({start: start, end: end});
            }
        }
        start = end + 1;
        end = end + 7;
        end = start === 1 && end === 8 ? 1 : end;
        if (end > numDays) {
            end = numDays;
        }
    }

    weeks.forEach(week => {
        var _s = parseInt(week.start, 10)+1,
            _e = parseInt(week.end,10)+1;
        console.log("Contracting "+ new Date(year, month, _s).toJSON().slice(0,10).split('-').reverse().join('/') + " - " + new Date(year, month, _e).toJSON().slice(0,10).split('-').reverse().join('/'));
        console.log(((_e-_s)+1)*8)
    });
    return weeks;
}
console.table(getWeeksStartAndEndInMonth(6, 2018, 'monday'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment