1 获取当前月份最后一天方法
1)使用Date对象获取当前年份和月份;
2)创建一个新的Date对象,设置日期为当前月份的下一个月的第0天(即当前月份的最后一天);
3)使用getDate()方法获取当前月份最后一天的日期。
const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; // 月份从0开始计算,需要加1 const lastDay = new Date(year, month, 0).getDate(); console.log(lastDay); //输出当前月份最后一天的日期
2 获取指定日期所在月份最后一天的方法
1)使用Date对象获取指定日期的年份和月份;
2)创建一个新的Date对象,设置日期为指定日期所在月份的下一个月的第0天(即指定日期所在月份的最后一天);
3)使用getDate()方法获取指定日期所在月份最后一天的日期。
const date = new Date('2021/09/15'); const year = date.getFullYear(); const month = date.getMonth() + 1; // 月份从0开始计算,需要加1 const lastDay = new Date(year, month, 0).getDate(); console.log(lastDay); //输出指定日期所在月份最后一天的日期