How can I get the 4 Mondays of a month with js?
This would return the fourth last monday of month [m] in year [y]
function lastmonday(y,m) {
var dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstmonday = false;
while (currentmonth === m){
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastmonday(2012,3); //=>Mon Mar 26 2012 00:00:00 GMT+0200
lastmonday(2012,2) //=>Mon Feb 27 2012 00:00:00 GMT+0100
lastmonday(1997,1) //=>Mon Jan 27 1997 00:00:00 GMT+0100
lastmonday(2012,4) //=>Mon Apr 30 2012 00:00:00 GMT+0200
To be more generic, this will deliver the last any weekday of a month:
function lastDayOfMonth(y,m,dy) {
var days = {sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}
,dat = new Date(y+'/'+m+'/1')
,currentmonth = m
,firstday = false;
while (currentmonth === m){
firstday = dat.getDay() === days[dy] || firstday;
dat.setDate(dat.getDate()+(firstday ? 7 : 1));
currentmonth = dat.getMonth()+1 ;
}
dat.setDate(dat.getDate()-7);
return dat;
}
// usage
lastDayOfMonth(2012,2,'tue'); //=>Tue Feb 28 2012 00:00:00 GMT+0100
lastDayOfMonth(1943,5,'fri'); //=>Fri May 28 1943 00:00:00 GMT+0200
For whoever may need, this is a general function to get every monday, tuesday, etc
getDatesOfDayOfWeek (year, month, dayOfWeek) {
const initialDate = new Date(year, month, 1);
const datesOfDayOfWeek = [];
while (initialDate.getDay() !== dayOfWeek) {
initialDate.setDate(initialDate.getDate() + 1);
}
while (initialDate.getMonth() === month) {
const nextDate = new Date(initialDate.getTime());
datesOfDayOfWeek.push(nextDate.getDate());
initialDate.setDate(initialDate.getDate() + 7);
}
return datesOfDayOfWeek;
}
The following function
will return all Mondays for the current month:
function getMondays() {
var d = new Date(),
month = d.getMonth(),
mondays = [];
d.setDate(1);
// Get the first Monday in the month
while (d.getDay() !== 1) {
d.setDate(d.getDate() + 1);
}
// Get all the other Mondays in the month
while (d.getMonth() === month) {
mondays.push(new Date(d.getTime()));
d.setDate(d.getDate() + 7);
}
return mondays;
}