获取某个月有多少天

题目:封装一个函数 getMonthLength(month),传入月份(Date 或字符串)返回该月天数。

function getMonthLength(month) {
  const date = new Date(month);
  const year = date.getFullYear();
  const _month = date.getMonth() + 1;
  // Date 的 day 参数传 0 会回退到上个月最后一天
  return new Date(year, _month, 0).getDate();
}

补充

补充:原笔记里有一段空 return days; 的占位函数,已删除。核心技巧是利用 new Date(year, month, 0):当 day 为 0 时,Date 会回退到上一个月最后一天,因此 getDate() 就得到当月总天数。