How can I get the 4 Mondays of a month with js?

后端 未结 2 2024
一个人的身影
一个人的身影 2020-12-01 11:54

I\'m building a chart where the x-axis should be the four weeks of a month. I would like to display only the four Mondays of that month.

I already have the cur

相关标签:
2条回答
  • 2020-12-01 11:59

    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;
    }
    
    0 讨论(0)
  • 2020-12-01 12:13

    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
    
    0 讨论(0)
提交回复
热议问题