(first of all, excuse my english, i'm a beginner)
let me explain the situation :
I would like to create charts using Google Charts Tool (give it a try, it's very helpful). This part is not really difficult...
The problem comes when i have a specific chart requiring in the x-axis the four weeks of a month : i would like to display on the screen only the four mondays in the currentmonth.
I already have got the currentMonth and the currentYear variables and i know how to get the first day of the month. all i need is how to get the four mondays of a month, in an array. And all of this in the same JavaScript file.
I'm pretty lost within my programming logic, and i've seen plenty of solutions wich fit not my case.
so, what do i have is :
var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear,currentMonth,1);
var firstWeekDay = firstDayofMonth.getDay();
and i would like to have something like this :
var myDates =
[new Date(firstMonday),new Date(secondMonday), new Date(thirdMonday),new Date(fourthMonday)]
Thank you for reading, and if you could help me... :)
Gaelle
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;
}
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
来源:https://stackoverflow.com/questions/9481158/how-to-get-the-4-monday-of-a-month-with-js