12

x 軸が 1 か月の 4 週間になるグラフを作成しています。その月の 4 つの月曜日だけを表示したいと思います。

私はすでに変数と変数を持っておりcurrentMonthcurrentYear月の最初の日を取得する方法を知っています。必要なのは、月の 4 つの月曜日を配列で取得することだけです。そして、これらすべてが同じ 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] の最後の第 4月曜日を返します。

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 に答える