Number of days in month

JavaScript, Date · Jun 13, 2021

Gets the number of days in the given month of the specified year.

  • Use the Date constructor to create a date from the given year and month.
  • Set the days parameter to 0 to get the last day of the previous month, as months are zero-indexed.
  • Use Date.prototype.getDate() to return the number of days in the given month.
const daysInMonth = (year, month) => new Date(year, month, 0).getDate();

daysInMonth(2020, 12)); // 31
daysInMonth(2024, 2)); // 29

More like this

  • Day of year

    Gets the day of the year (number in the range 1-366) from a Date object.

    JavaScript, Date · Oct 19, 2020

  • Number of seconds to ISO format

    Returns the ISO format of the given number of seconds.

    JavaScript, Date · Oct 13, 2021

  • Add days to date

    Calculates the date of n days from the given date, returning its string representation.

    JavaScript, Date · Nov 28, 2020