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

前端 未结 4 1058
长情又很酷
长情又很酷 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 19:14

    Given

    var year = 2011;
    var month = 3;
    var week = 2;
    

    and

    var firstDateOfMonth = new Date(year, month - 1, 1); // Date: year-month-01
    
    var firstDayOfMonth = firstDateOfMonth.getDay();     // 0 (Sun) to 6 (Sat)
    
    var firstDateOfWeek = new Date(firstDateOfMonth);    // copy firstDateOfMonth
    
    firstDateOfWeek.setDate(                             // move the Date object
        firstDateOfWeek.getDate() +                      // forward by the number of
        (firstDayOfMonth ? 7 - firstDayOfMonth : 0)      // days needed to go to
    );                                                   // Sunday, if necessary
    
    firstDateOfWeek.setDate(                             // move the Date object
        firstDateOfWeek.getDate() +                      // forward by the number of
        7 * (week - 1)                                   // weeks required (week - 1)
    );
    
    var dateNumbersOfMonthOnWeek = [];                   // output array of date #s
    var datesOfMonthOnWeek = [];                         // output array of Dates
    
    for (var i = 0; i < 7; i++) {                        // for seven days...
    
        dateNumbersOfMonthOnWeek.push(                   // push the date number on
            firstDateOfWeek.getDate());                  // the end of the array
    
        datesOfMonthOnWeek.push(                         // push the date object on
            new Date(+firstDateOfWeek));                 // the end of the array
    
        firstDateOfWeek.setDate(
            firstDateOfWeek.getDate() + 1);              // move to the next day
    
    }
    

    then

    • dateNumbersOfMonthOnWeek will have the date numbers of that week.
    • datesOfMonthOnWeek will have the date objects of that week.

    While this may seem like it is overkill for the job, much of this is required to make it work in all situations, like when the date numbers cross over to another month. I'm sure it could be optimised to be less verbose, though.

提交回复
热议问题