Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading