Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

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

/**
 * 获取当前月份有多少天
 * @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();
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.