You can find the last day of the month for a given date in JavaScript using the following steps:
Date
object with the given date.Date
object using the getMonth()
method. Note that the getMonth()
method returns a zero-based index, so you need to add 1 to get the actual month.Date
object using the getFullYear()
method.Date
object using the next month and set the day to 0. The day set to 0 means the last day of the previous month.Date
object using the getDate()
method.Here's an example code snippet that implements the above steps:
function getLastDayOfMonth(date) {
const month = date.getMonth() + 1;
const year = date.getFullYear();
const nextMonth = month + 1;
const lastDayOfMonth = new Date(year, nextMonth, 0).getDate();
return lastDayOfMonth;
}
// Example usage
const date = new Date('2022-02-15'); // Replace with your desired date
const lastDay = getLastDayOfMonth(date);
console.log(lastDay); // Output: 28
In the example above, the given date is "2022-02-15"
, and the last day of the month is 28
since February 2022 has 28 days. You can replace the date
variable with your desired date in the new Date()
constructor to get the last day of the month for any given date.