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

JavaScript get last day of Month – based on Year, Month and day

I need a JS function to get the last date of the month.
as an example, I need to get the last Wednesday of this month.

I will pass Year, Month and day as a arguments.

getLastDayOfMonth('2022', '02', 'Wednesday');

function getLastDayOfMonth(year, month, day){

     // Output should be like this

       2022-02-23    

    (this is last Wednesday of the month, according to the arguments- Year, month and Day)
}

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

>Solution :

Create a Date instance with the last day of the month then work backwards one day at a time until you match the day of the week you’re after

const dayIndex = {
  Sunday: 0,
  Monday: 1,
  Tuesday: 2,
  Wednesday: 3,
  Thursday: 4,
  Friday: 5,
  Saturday: 6
}

const getLastDayOfMonth = (year, month, dow) => {
  const day = dayIndex[dow]
  
  // init as last day of month
  const date = new Date(Date.UTC(parseFloat(year), parseFloat(month), 0))
  
  // work back one-day-at-a-time until we find the day of the week
  while (date.getDay() != day) {
    date.setDate(date.getDate() - 1)
  }
  
  return date
}

console.log(getLastDayOfMonth("2022", "02", "Wednesday"))

The numeric values are parsed as numbers so we don’t run into problems with zero-padded octal numbers.

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