30秒学会 JavaScript 片段 · 2023年4月8日

30秒学会 JavaScript 片段 – Number of days in month

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

翻译自:https://www.30secondsofcode.org/js/s/days-in-month