根据 javascript 中的选定月份获取星期一日期

Get mondays dates based on selected month in javascript

此问题与 this SO 问题相关,提供的解决方案运行良好。但是,就我而言,我想从下拉菜单中获取选定月份的星期一日期。

我试过的代码是:

var d = new Date(),
  month = d.getMonth(),
  mondays = [],
  mondaysChange = [];
//console.log("current month is: "+month);
//console.log("current months mondays are: " + getMondays());

$("#ddlMonths option").filter(function() {
  return this.value == month;
}).attr('selected', true);

$('#ddlMonths').on('change', function(e) {
  var m = $("option:selected", this).val();
  console.log("selected month: " + m);
  var str = getMondaysChange(m);
  console.log("selected months mondays are: " + str);
});

function getMondaysChange(m) {
  d.setDate(1);
  d.setMonth(m);
  console.log("you have selected: " + d + " month");
  while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
  }

  // Get all the other Mondays in the month
  while (d.getMonth() === m) {
    mondaysChange.push(new Date(d.getTime()));

    d.setDate(d.getDate() + 7);
  }

  return mondaysChange;
}

function getMondays() {
  d.setDate(1);

  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;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js"></script>

<div class="data-block">
  <div class="data-container">
    <header>
      <h2>
                                        Track</h2>

    </header>
    <div class="form-horizontal">
      <div class="form-group">
        <label for="CAASRTUserName" class="col-sm-2 control-label">Resource</label>
        <div class="col-sm-10">
          <input id="CAASRTUserName" type="text" data-bind="value: Vendor" placeholder="" class="form-control hasclear">
        </div>
      </div>
      <div class="form-group has-feedback">
        <label for="InvoiceTotal" class="col-sm-2 control-label">Enter for Month</label>
        <div class="col-sm-10">
          <select id="ddlMonths" class="form-control">
            <option value="0">January</option>
            <option value="1">February</option>
            <option value="2">March</option>
            <option value="3">April</option>
            <option value="4">May</option>
            <option value="5">June</option>
            <option value="6">July</option>
            <option value="7">August</option>
            <option value="8">September</option>
            <option value="9">October</option>
            <option value="10">November</option>
            <option value="11">December</option>
          </select>
        </div>
      </div>
      <!-- <div class="form-group">
                                        <div class="col-sm-offset-2 col-sm-10">
                                            <button id="btnTrack" data-bind="click: Submit" class="btn btn-default">
                                                Submit
                                            </button>
                                        </div>
                                    </div> --></div>
    <br>
    <div class="row">
      <div class="col-md-12">
        <!-- <h4>
                                            <span id="mySpanCur">Current Week</span>
                                        </h4> -->
        <div id="divtblTrack" class="plan">
          <table id="tblTrack" class="table table-bordered">
            <thead>
              <tr>
                <th>Parent Activity</th>
                <th>Hrs/ Wk</th>
                <th>Activity</th>
                <th><span id="week1"></span>

                </th>
                <th><span id="week2"></span>

                </th>
                <th><span id="week3"></span>

                </th>
                <th><span id="week4"></span>

                </th>
                <th>Comments</th>
                <th>Total</th>
                <th style="display:none">PlanEntryId</th>
              </tr>
            </thead>
            <tfoot>
              <tr>
                <td></td>
                <td id="HrsByWkSum">204</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td id="TotalSum">0</td>
                <td style="display:none"></td>
              </tr>
            </tfoot>
            <tbody>
              <tr>
                <td class="emptyTd"><span>Analytics</span>

                </td>
                <td class="hoursbyweek emptyTd"><span>67</span>

                </td>
                <td class="DD">
                  <select class="form-control" readonly="readonly">
                    <option value="Select">Select</option>
                  </select>
                </td>
                <td class="mon">
                  <input type="text" id="txtMon" class="form-control" style="width:40px;" value="" />
                </td>
                <td class="tue">
                  <input type="text" id="txtTue" class="form-control" style="width:40px;" value="" />
                </td>
                <td class="wed">
                  <input type="text" id="txtWed" class="form-control" style="width:40px;" value="" />
                </td>
                <td class="thu">
                  <input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
                </td>
                <td>
                  <input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
                </td>
                <td class="tot emptyTdTot"></td>
                <td style="display:none">3</td>
                <td>
                  <button class="btn btn-primary btn-xs myBtn">Add</button>
                </td>
              </tr>
              <tr>
                <td class="emptyTd"><span>General Admin</span>

                </td>
                <td class="hoursbyweek emptyTd"><span>36</span>

                </td>
                <td class="DD">
                  <select class="form-control" readonly="readonly">
                    <option value="Select">Select</option>
                  </select>
                </td>
                <td class="mon">
                  <input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
                </td>
                <td class="tue">
                  <input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
                </td>
                <td class="wed">
                  <input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
                </td>
                <td class="thu">
                  <input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
                </td>
                <td>
                  <input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
                </td>
                <td class="tot emptyTdTot"></td>
                <td style="display:none">2</td>
                <td>
                  <button class="btn btn-primary btn-xs myBtn">Add</button>
                </td>
              </tr>
              <tr>
                <td class="emptyTd"><span>Reports</span>

                </td>
                <td class="hoursbyweek emptyTd"><span>56</span>

                </td>
                <td class="DD">
                  <select class="form-control" readonly="readonly">
                    <option value="Select">Select</option>
                  </select>
                </td>
                <td class="mon">
                  <input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
                </td>
                <td class="tue">
                  <input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
                </td>
                <td class="wed">
                  <input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
                </td>
                <td class="thu">
                  <input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
                </td>
                <td>
                  <input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
                </td>
                <td class="tot emptyTdTot"></td>
                <td style="display:none">6</td>
                <td>
                  <button class="btn btn-primary btn-xs myBtn">Add</button>
                </td>
              </tr>
              <tr>
                <td class="emptyTd"><span>Time not working</span>

                </td>
                <td class="hoursbyweek emptyTd"><span>45</span>

                </td>
                <td class="DD">
                  <select class="form-control" readonly="readonly">
                    <option value="Select">Select</option>
                  </select>
                </td>
                <td class="mon">
                  <input type="text" id="txtMon" class="form-control" style="width:40px;" value="">
                </td>
                <td class="tue">
                  <input type="text" id="txtTue" class="form-control" style="width:40px;" value="">
                </td>
                <td class="wed">
                  <input type="text" id="txtWed" class="form-control" style="width:40px;" value="">
                </td>
                <td class="thu">
                  <input type="text" id="txtThu" class="form-control" style="width:40px;" value="">
                </td>
                <td>
                  <input type="text" id="txtComments" class="form-control" style="width:90px;" value="">
                </td>
                <td class="tot emptyTdTot"></td>
                <td style="display:none">1</td>
                <td>
                  <button class="btn btn-primary btn-xs myBtn">Add</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="col-md-12">
        <div class="form-group">
          <div class="pull-right">
            <button id="btnSubmit" data-bind="click: Submit" class="btn btn-default">Save</button>
          </div>
        </div>
      </div>
    </div>
    <br>
  </div>
</div>

Jsbin 同样是here。我正在设置更改下拉列表的月份,但我仍然想知道为什么 mondaysChange 数组返回空。谁能查一下?

A momentjs 相同的解决方案也很好,但我似乎无法轻易获得它。

我认为问题在于比较 d.getMonth() === m,您将 m 作为选定的选项值传递,它将是字符串类型,而 d.getMonth() 是数字类型。

所以试试

//empty the array
mondaysChange.length = 0;

//change the type of m to number
m = +m;

d.setDate(1);
d.setMonth(m);
console.log("you have selected: " + d + " month");
while (d.getDay() !== 1) {
    d.setDate(d.getDate() + 1);
}

// Get all the other Mondays in the month
while (d.getMonth() === m) {
    mondaysChange.push(new Date(d.getTime()));

    d.setDate(d.getDate() + 7);
}

演示:Fiddle, Problem

一周开始使用这个

var startDay = 0;
var d =today.getDay();
var weekStart = new Date(today.valueOf() - (d<=0 ? 7-startDay:d-startDay)*86400000); //rewind to start day
var nextweekStart =new Date(weekStart.valueOf() + (7)*86400000);//get first day of next week
var prevweekStart =new Date(weekStart.valueOf() - (7)*86400000);//get first day of prev week

如果开始日期=0; return 星期日然后使用 1 而不是 0 作为: //0=星期日,1=星期一等

这是一个更通用的函数,用于检索从给定日期算起的一个月中某一天的所有日期。查看代码片段,它在选择器的更改处理程序中使用。

  function getAllInstancesOfDayInMonth(fordate, forday) {
    fordate.setDate(1);
    var start  = getStartDay(fordate, forday)
       ,month  = fordate.getMonth()
       ,result = [start];

    while (fordate.getMonth() == month) {
      result.push(new Date(fordate.setDate(fordate.getDate()+7)));
    } 

    return result.slice(0,-1);

    function getStartDay(d, forday) {
     return d.getDay() != +forday
            ? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
            : new Date(d);
    }

  }

(function () {
 
   document.querySelector('#ddlMonths')
    .addEventListener('change', getMondays);
  
   var result = document.querySelector('#result');
  
   result.innerHTML = '<h3>all mondays in January 2015</h3>';
   result.innerHTML += getAllInstancesOfDayInMonth(
                           new Date([2015,1,1].join('/')), 1
                        ).join('\n');
  
  function getMondays(e){
    var year = this.getAttribute('data-year')
       ,month = +this.options[this.selectedIndex].value
       ,monthstr = this.options[this.selectedIndex].innerHTML;
    
    result.innerHTML = '<h3>all mondays in '+monthstr+' '+ year+'</h3>';
    result.innerHTML += getAllInstancesOfDayInMonth(
                           new Date([year,month+1,1].join('/')), 1
                        ).join('\n');
  }
  
  function getAllInstancesOfDayInMonth(fordate, forday) {
    fordate.setDate(1);
    var start  = getStartDay(fordate, forday)
       ,month  = fordate.getMonth()
       ,result = [start];
    
    while (fordate.getMonth() == month) {
      result.push(new Date(fordate.setDate(fordate.getDate()+7)));
    } 
    
    return result.slice(0,-1);
    
    function getStartDay(d, forday) {
     return d.getDay() != +forday
            ? ( d.setDate( d.getDate() + 1 ), getStartDay(d, forday) )
            : new Date(d);
    }
    
  }
  
}())
body {font: 12px/15px normal verdana, arial; margin:1.5em; }
<select id="ddlMonths" class="form-control" data-year="2015">
  <option value="0">January</option>
  <option value="1">February</option>
  <option value="2">March</option>
  <option value="3">April</option>
  <option value="4">May</option>
  <option value="5">June</option>
  <option value="6">July</option>
  <option value="7">August</option>
  <option value="8">September</option>
  <option value="9">October</option>
  <option value="10">November</option>
  <option value="11">December</option>
</select> Select a month to retrieve all mondays of it

<pre id="result"></pre>