Home > Net >  Get weeks in a month as array with Day Name and Date
Get weeks in a month as array with Day Name and Date

Time:06-28

I have a code that return weeks start and end date in a month but I need it return full week with date ,day, month

month start from 0-11

function getFullWeeksStartAndEndInMonth (month, year) {
    let weeks = [],
        firstDate = new Date(year, month, 1),
        lastDate = new Date(year, month   1, 0),
        numDays = lastDate.getDate()

    let start = 1
    let end
    if (firstDate.getDay() === 1) {
        end = 7
    } else if (firstDate.getDay() === 0) {
        let preMonthEndDay = new Date(year, month, 0)
        start = preMonthEndDay.getDate() - 6   1
        end = 1
    } else {
        let preMonthEndDay = new Date(year, month, 0)
        start = preMonthEndDay.getDate()   1 - firstDate.getDay()   1
        end = 7 - firstDate.getDay()   1
        weeks.push({
            start: start,
            end: end
        })
        start = end   1
        end = end   7
    }
    while (start <= numDays) {
        weeks.push({
            start: start,
            end: end
        });
        start = end   1;
        end = end   7;
        end = start === 1 && end === 8 ? 1 : end;
        if (end > numDays && start <= numDays) {
            end = end - numDays
            weeks.push({
                start: start,
                end: end
            })
            break
        }
    }
    return weeks
}

How to get full week date day month not just start and end date like this

0: {date:30,month:"May",day:"Monday"},{date:31,month:"May",day:"Tuesday"},{date:1,month:"June",day:"Wednesday"},...

CodePudding user response:

Here you go

If you need anything explained let me know, it's just a simple .map that outputs seven objects for the week with the required info

at the moment, it's a nested array - each item in the outer array is an array for a week

if you want to flatten it, uncomment the .flat(Infinity)

function getFullWeeksStartAndEndInMonth (month, year) {
    let weeks = [],
        firstDate = new Date(year, month, 1),
        lastDate = new Date(year, month   1, 0),
        numDays = lastDate.getDate()

    let start = 1
    let end
    if (firstDate.getDay() === 1) {
        end = 7
    } else if (firstDate.getDay() === 0) {
        let preMonthEndDay = new Date(year, month, 0)
        start = preMonthEndDay.getDate() - 6   1
        end = 1
    } else {
        let preMonthEndDay = new Date(year, month, 0)
        start = preMonthEndDay.getDate()   1 - firstDate.getDay()   1
        end = 7 - firstDate.getDay()   1
        weeks.push({
            start: start,
            end: end
        })
        start = end   1
        end = end   7
    }
    while (start <= numDays) {
        weeks.push({
            start: start,
            end: end
        });
        start = end   1;
        end = end   7;
        end = start === 1 && end === 8 ? 1 : end;
        if (end > numDays && start <= numDays) {
            end = end - numDays
            weeks.push({
                start: start,
                end: end
            })
            break
        }
    }
    // *** the magic starts here
    return weeks.map(({start, end}, index) => {
      let begin = new Date(year, month, start), 
        finish = new Date(year, month, end);
      if (start > end) {
        if(!index) {
          begin = new Date(year, month-1, start);
        } else {
          finish = new Date(year, month 1, end);
        }
      }
      const ret = [];
      while(begin.getDate() !== finish.getDate()   1) {
        ret.push({
            date: begin.getDate(),
            month: begin.toLocaleString('en', {month: 'long'}),
            day: begin.toLocaleString('en', {weekday: 'long'}),
          })
        begin.setDate(begin.getDate()   1);
      }
      return ret;
    })//.flat(Infinity);
}
console.log(getFullWeeksStartAndEndInMonth(5, 2022))

CodePudding user response:

The output example in OP:

/* 
The `0:` implies that everything to the right of it is first element of an array
If so then it needs brackets `[]`, or it's a string which needs quotes ""
 */
0: {date: 30, month: "May", day: "Monday"},
   {date: 31, month: "May", day: "Tuesday"},
   {date: 1, month: "June", day: "Wednesday"},...

is wrong, unless it's one huge string in a single array which would be pointless. The example provided returns an array of objects:

[
  {date: 26, month: "May", day: "Thursday"},
  {date: 27, month: "May", day: "Friday"},
  {date: 28, month: "May", day: "Saturday"},
  {date: 29, month: "May", day: "Sunday"},...
]

Details are commented in example

/**
 * @desc Given a start string date and an end string date, return
 * each day as an object consisting of {date, month, weekday}
 * in an array
 * @param {string<date>} from - A string in this format yyyy-mm-dd
 * @param {string<date>} to - See previous
 * @return {array<object>} An array of objects with the following:
 *         {date: {number}, month: {string}, day: {string}}
 */
function dateRange(from, to) {
  // Convert the parameters into Date objects
  const start = new Date(from)
  const end = new Date(to);
  // Define array to return
  let range = [];
  
  /*
  While the start date is less than or equal to the end date...
  ...get a new date object setting it's date number ahead by 1...
  ...next get the new date...
  ...then the long version of the month...
  ...and then the long version of the weekday...
  ...create an object with those values matched to these keys:
     date, month, day...
  ...add the object to the range array
  */
  while(start <= end) {
    const next = new Date(start.setDate(start.getDate() 1));
    const date = next.getDate();
    const month = next.toLocaleString('default', {month: 'long'});
    const day = next.toLocaleString('default', {weekday: 'long'});
    const dayObj = Object.assign({}, {date: date, month: month, day: day});
    range.push(dayObj);
  }
  // After the while loop, return the range array
  return range;
}

console.log(dateRange('2022-05-26', '2022-06-12'));

  • Related