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)
}
>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.