fezaoduke / fe-practice-hard

晚练课
69 stars 6 forks source link

第 93 期(W3C 标准-JavaScript-Date):获取指定月份有多少天 #96

Open wingmeng opened 5 years ago

wingmeng commented 5 years ago

获取某个月份有多少天是个很实用的技巧,做日历相关的组件或插件时很常见。

/**
 * 获取当前月份有多少天
 * @param {string | number} [dateStr] - 日期字符串,选填。格式:yyyy-MM-dd 或 yyyy/MM/dd 或 UTC 毫秒数
 * @return {number} 指定月份的天数,若 dateStr 为空,则返回当前月的天数
 */
function getCurMonthDays(dateStr) {
  var date = new Date();
  var lastDate;

  if (
    typeof dateStr === 'number' ||
    (typeof dateStr === 'string' && dateStr.trim())
  ) {
    date = new Date(dateStr)
  }

  lastDate = new Date(date.getFullYear(), date.getMonth() + 1, 0);

  return lastDate.getDate();
}

测试用例:

const test = [
  {
    it:     '2019-08-22',
    expect: 31
  }, {
    it:     '2019-02-12',
    expect: 28
  }, {
    it:     '2019-12-31',
    expect: 31
  }, {
    it:     '2019-01-30',
    expect: 31
  }
];

test.map(item => {
  const result = getCurMonthDays(item.it);
  const isPassed = result === item.expect;

  console.group(result);
  isPassed ? console.log('%c√ Pass', 'color: green') :
    console.log('%c× Failed', 'color: red');
  console.groupEnd();
});