12

我正在构建一个图表,其中 x 轴应该是一个月的四个星期。我只想显示那个月的四个星期一。

我已经有了currentMonthcurrentYear变量,而且我知道如何获得本月的第一天。我所需要的只是将一个月的四个星期一放在一个数组中。所有这些都在同一个 JavaScript 文件中。

我在我的编程逻辑中迷失了方向,而且我看到了很多不适合我的用例的解决方案。

现在,我有:

var date = new Date();
var currentYear = date.getFullYear();
var currentMonth = date.getMonth();
var firstDayofMonth = new Date(currentYear, currentMonth, 1);
var firstWeekDay = firstDayofMonth.getDay();

但我想要这样的东西:

var myDates = [
    new Date(firstMonday),
    new Date(secondMonday),
    new Date(thirdMonday),
    new Date(fourthMonday),
];
4

2 回答 2

35

以下function将返回当月的所有星期一:

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;
}
于 2012-02-28T11:58:23.547 回答
4

这将返回[y] 年 [m] 月的倒数第四个星期一

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

更通用地说,这将提供一个月的最后一个工作日:

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
于 2012-02-28T12:14:52.473 回答