hamzasgd
hamzasgd

Reputation: 251

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

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"},...

Upvotes: 0

Views: 1143

Answers (2)

Bravo
Bravo

Reputation: 6263

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) => {
        const sub = +(start > end && index === 0);
        return Array.from({length: 7}, (_, index) => {
            const date = new Date(year, month - sub, start + index);
            return {
                date: date.getDate(),
                month: date.toLocaleString('en', {month: 'long'}),
                day: date.toLocaleString('en', {weekday: 'long'}),
            };
        });
    })//.flat(Infinity);
}
console.log(getFullWeeksStartAndEndInMonth(6, 2022))

Upvotes: 2

zer00ne
zer00ne

Reputation: 44086

The output example in OP:

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

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 "". In the OP the result looks like an array with another array that has objects. The outer array is pointless. The example provided returns an array of objects, which is one of the most commonly used data-structures:

[
  {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'));

Upvotes: 1

Related Questions