Skip to content

[js] 第736天 写一个方法根据日期获取当月有多少天 #3846

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第736天 写一个方法根据日期获取当月有多少天

3+1官网

我也要出题

Activity

githubzml

githubzml commented on Apr 21, 2021

@githubzml
function getDateNum(params) {
  let temp = null;
  let getYear = params.getFullYear();
  let getMonth = params.getMonth() + 1;
  // new Date(year, month, 0).getDate()
  temp = new Date(getYear, getMonth, 0).getDate();
  return temp;
}
console.log('结果:', getDateNum(new Date()));
ghost

ghost commented on Apr 21, 2021

@ghost
/**
 * 根据日期获取当月天数
 * @param {string|number} month - 月份
 * @param {string|number} [year] - 年份
 * @returns {number} 天数
 */
function daysInMonth(month, year) {
    year = year || new Date().getFullYear();
    return new Date(year, month, 0).getDate();
}

daysInMonth(8, 2019); // => 31
daysInMonth(2, 2020); // => 29
daysInMonth(2); // => 28
yxj1028530975

yxj1028530975 commented on Apr 22, 2021

@yxj1028530975

function getDateDays(year,month){ return new Date(year,month,0).getDate()//获得是标准时间,需要getDate()获得天数 } getDateDays(2021,5) // =>31

alanhe421

alanhe421 commented on Apr 22, 2021

@alanhe421
const daysInMonth = (date) => new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@alanhe421@githubzml@yxj1028530975

        Issue actions

          [js] 第736天 写一个方法根据日期获取当月有多少天 · Issue #3846 · haizlin/fe-interview