Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue Aug 22, 2019 · 0 comments
Open

Comments

@wingmeng
Copy link
Collaborator

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

/**
 * 获取当前月份有多少天
 * @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();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant