获取某月的天数(最后一天的日期)📅

105 阅读2分钟

我正在参加「掘金·启航计划」

前言

想从零开发一个DatePicker组件,首先需要获取某月有多少天
我们应该都有印象的一段顺口溜:
一三五七八十腊,三十一天永不差;
四六九冬三十天;
平年二月二十八,闰年二月二十九。
只有二月份比较特殊,要区分平闰年

顺口溜实现

  • [add] 平闰年判断

闰年: 年份(year)能被4整除但不能被100整除,或者能被400整除。

// 是否是闰年
function isLeapYear(year?: number): boolean {
  if (!year) {
    // 如果没有传参数,则取当前年份
    year = new Date().getFullYear();
  }
  if (year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0)) {
    return true;
  }
  return false;
}
// 获取某月的天数
function getMonthDays(year?: number, month?: number): number {
  // 声明一个31天大的月份集合
  const daysIs31 = [1, 3, 5, 7, 8, 10, 12];
  const commonYearFebDays = 28;
  const leapYearFebDays = 29;
  const thirtyDays = 30;
  const thirtyOneDays = 31;
  if (!year || !month) {
    // 没有传年或月的参数时,取当前年份和月份
    const nowDate = new Date();
    year = nowDate.getFullYear();
    // 月份 getMonth 返回[0,1,2,3,4,5,6,7,8,9,10,11] 所以要加一处理
    month = nowDate.getMonth() + 1;
  }
  if (month === 2) {
    // 二月份做平闰年判断
    return isLeapYear(year) ? leapYearFebDays : commonYearFebDays;
  }
  return daysIs31.includes(month) ? thirtyOneDays : thirtyDays;
}

Date的越界自动处理

// 获取某月的天数
function getMonthDays(year?: number, month?: number): number {
  if (!year || !month) {
    // 没有传年或月的参数时,取当前年份和月份
    const nowDate = new Date();
    year = nowDate.getFullYear();
    month = nowDate.getMonth() + 1;
  }
  // 这里Date的第三个参数传零
  // 正常获取某月某日时间时,month是需要减一处理
  // e.g 2022-09-25 == new Date(2022, 8, 25)
  // 获取9月的天数 new Date(2022, 9, 0)== 取得是十月的第零天,Date越界处理放回九月的最后一天
  return new Date(year, month, 0).getDate();
}

后记

个人博客 | Botaoxy (chengbotao.github.io)
chengbotao (Chengbotao) (github.com)

感谢阅读,敬请斧正!