user3233787
user3233787

Reputation: 377

Moment.js get the date based on the given weekday and date

I would like to get the date based on the given weekday and date. Let's say:

const date = "2022-08-29"; // Monday
const week = "Wednesday"; OR const week = 3;

The resulting date should be "2022-08-31" since the Wednesday of that week is on the 31st.

I have tried adding some days, but I can say it's not the right approach since if the date would start at a later point, let's say:

const date = "2022-08-31"; // Wednesday
const week = "Tuesday"; OR const week = 2;

Then added 2 days starting from 31st would result to 2022-09-02 which is on Sep 2nd. The correct result would be 2022-08-30 since the Tuesday of that week is on the 30th. How to achieve this one?

Upvotes: 0

Views: 67

Answers (1)

Phil
Phil

Reputation: 164742

Wind the date back to the start of the week then add the number of days to bring it up to the nominated day.

The current day of the week can be determined using Date.prototype.getDay().

const days = {Monday: 1, Tuesday: 2, Wednesday: 3, Thursday: 4, Friday: 5, Saturday: 6, Sunday: 7};

const getDayOfWeek = (dateStr, weekDay) => {
  // turn string values into a day offset
  // subtract 1 to get offset from the start of the week
  const dayOffset = (typeof weekDay === "number" ? weekDay : days[weekDay]) - 1;
  
  // Parse date string
  const date = new Date(dateStr);
  
  // Offset for Monday as the start of the week
  const weekStartOffset = (date.getDate() + 6) % 7;
  
  // Alter the date
  date.setDate(date.getDate() - weekStartOffset + dayOffset);
  return date;
};

console.info("Week of Monday 29th Aug -> Wednesday");
console.log(getDayOfWeek("2022-08-29", "Wednesday"));

console.info("Week of Wednesday 31st Aug -> Tuesday");
console.log(getDayOfWeek("2022-08-31", "Tuesday"));

console.info("Week of Sunday 28th Aug -> Monday");
console.log(getDayOfWeek("2022-08-28", "Monday"));
.as-console-wrapper { max-height: 100% !important; }

Upvotes: 1

Related Questions