How to check if a week arrangement is part of the month

Viewed 24

I would like to be able to validate in an arrangement that brings me the week, if it is part of the month

I pass a start_date to my function, then check if that date is part of a week that starts on Monday and ends on Sunday, so if I pass it today, Monday 5th September 2022, it will return something like this. week :

[
  "2022-09-05", // Monday
  "2022-09-06", // Tuesday
  "2022-09-07", // Wednesday
  "2022-09-08", // Thursday
  "2022-09-09", // Friday
  "2022-09-10", // Saturday
  "2022-09-11" // Sunday
]

Although that's fine, but I need some validations that so far confuse me a bit, I need to be able to tell my algorithm to validate if the week that it brings is part of the month that is happening, that is, it is missing the date. "2022-09-30", the month is "9", I mean September, so the array is expected to return

[
  "2022-09-26",
  "2022-09-27",
  "2022-09-28",
  "2022-09-29",
  "2022-09-30"
]

and I would have to return it like this, because that's the last week of the month, so the counter would end there. And then it started again, but validating the following month and so on.

So in the end what I want to return is the week of a month, from Monday to Sunday, validating only the weeks of the month.

Any help would be appreciated.

export function ValidateWeek(date_start: any) {
  let curr: Date = date_start;
  const date = new Date(curr);
  let week: any[] = [];
  for (let i = 1; i <= 7; i++) {
    let first = date.getDate() - date.getDay() + i;
    let day = new Date(date.setDate(first - 1))
    week.push(day)
  }
  let convertWeek: any = [];
  week.forEach(dateT => {
    const newConvertDate = dateT.toISOString().substring(0, 10);
    convertWeek.push(newConvertDate)
  });
  return convertWeek;
}
1 Answers

First, we set our date backwards in time to last monday. Then going forward one by one over a week. Every time date is within same month of input date, we push it to result.

var date_start = "2022-10-01"
var d = new Date(date_start)
var month = d.getMonth();
var day = d.getDay();
var offset = day - 1
d.setDate(d.getDate() - offset);
var result = [];
for (var i = 0; i < 7; i++) {
  if (d.getMonth() === month) {
    result.push(new Date(d.getTime()));
  }
  d.setDate(d.getDate() + 1);
}
console.log(result)

Related