在javascript中根据所选月份获取星期一日期

时间:2015-03-02 11:49:49

标签: javascript datetime momentjs

此问题与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>
&#13;
&#13;
&#13;

同样的Jsbin是here。我正在设置更改下拉列表的月份,我仍然想知道为什么mondaysChange数组返回空。任何人都可以检查一下吗?

同样的momentjs解决方案也很好,我似乎无法轻易搞定。

3 个答案:

答案 0 :(得分:2)

开始一周使用此

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

如果startDay = 0;返回星期日然后使用1代替0作为: // 0 =星期日,1 =星期一等。

答案 1 :(得分:1)

我认为问题是比较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);
}

演示:FiddleProblem

答案 2 :(得分: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>