Get the days in a Week in Javascript, Week starts on Sunday

前端 未结 4 1011
长情又很酷
长情又很酷 2021-01-19 18:29

Here\'s the given input from the user:

Year = 2011, Month = 3 (March), Week = 2

I want to get the days in week 2 of March 2011 in JavaScript.

e.g. Su

4条回答
  •  别那么骄傲
    2021-01-19 18:48

    Assuming that the first week of the month is the one with the first of the month in it, then the following function will return the date of the first day of the week given year, month and week number:

    /* 
       Input year, month and week number from 1
       Returns first day in week (Sunday) where
       first week is the first with 1st of month in it
    */
    function getFirstDayOfWeek(y, m, w) {
      var d = new Date(y, --m);
      d.setDate(--w * 7 - d.getDay() + 1);
      return d;
    }
    
    alert(getFirstDayOfWeek(2011,3, 2)); // Sun Mar 06 2011
    

    To get the rest of the days, just loop 6 times adding one to the date each time, e.g.

    function getWeekDates(y, m, w) {
      var d = getFirstDayOfWeek(y, m, w)
      var week = [new Date(d)];
      var i = 6;
      while (i--) {
        week.push(new Date(d.setDate(d.getDate() + 1)));
      }
      return week;
    }
    
    // Show week of dates
    var week = getWeekDates(2011,3, 2);
    for (var i=0, iLen=week.length; i

提交回复
热议问题