[JS] Pass in a date and return the number of days in the month where the date is located


/**
 * 传入一个日期,返回该日期所在月份的天数
 * @param date 传入一个相对日期或者字符串日期
 * @returns 当前日期月份的天数
 */
const getDaysInMonth = (date) => {
    
    
    // 使用 Date 对象的构造函数创建一个新的日期对象
    const newDate = new Date(date);
    // 获取该日期所在月份的下一个月份
    const nextMonth = newDate.getMonth() + 1;
    // 设置日期对象的月份为下一个月份的第 0 天
    newDate.setMonth(nextMonth, 0);
    // 返回该日期所在月份的天数
    return newDate.getDate();
};


For more information about date and time processing, please click here to view

Guess you like

Origin blog.csdn.net/weixin_44244230/article/details/132087194