How to find the last day of the month for a given date in JavaScript?

You can find the last day of the month for a given date in JavaScript using the following steps:

  1. Create a JavaScript Date object with the given date.
  2. Get the current month from the 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.
  3. Get the current year from the Date object using the getFullYear() method.
  4. Increment the month by 1 to get the next month.
  5. Create a new 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.
  6. Get the day from the new 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.