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

How to get the quantity of a given weekday in a particular month?

How to get the quantity of a given weekday in a particular month? For example, get the quantity of Sundays in Jan 2023 or get the quantity of Tuesday in Feb 2023

>Solution :

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

function getWeekdayCount(year, month, weekday) {
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const count = Math.floor((lastDay.getDate() - firstDay.getDate() + (firstDay.getDay() + 7 - weekday) % 7) / 7);
  
  return count;
}

// Example usage:
const year = 2023;
const month = 0; // 0 = January, 1 = February, ..., 11 = December
const weekday = 0; // 0 = Sunday, 1 = Monday, ..., 6 = Saturday

const count = getWeekdayCount(year, month, weekday);
console.log(count); // Output: Number of occurrences of the weekday in the specified month

The formula (lastDay.getDate() - firstDay.getDate() + (firstDay.getDay() + 7 - weekday) % 7) / 7 calculates the number of occurrences of the specified weekday in the month. It subtracts the day of the week of the first day from the day of the week of the last day, adds 7, and takes the modulo 7 to ensure a positive result. Finally, it divides the result by 7 to get the count of occurrences.

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