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

drexsien picture drexsien · Jul 18, 2011 · Viewed 8.1k times · Source

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. Sunday 6th, Monday 7th, Tuesday 8th, Wednesday 9th, Thursday 10th, Friday 11th, Saturday 12th

Any ideas? Thanks!

Answer

Delan Azabani picture Delan Azabani · Jul 18, 2011

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.