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)
}
CodePudding user response:
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 normaliseDay = day => day.trim().toLowerCase()
const dayIndex = new Map([
["sunday", 0],
["monday", 1],
["tuesday", 2],
["wednesday", 3],
["thursday", 4],
["friday", 5],
["saturday", 6],
])
const getLastDayOfMonth = (year, month, dow) => {
const day = dayIndex.get(normaliseDay(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.
