JS获取当月最后一天用法介绍

发布时间 2024-01-09 11:18:53作者: DAYTOY-105

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); //输出指定日期所在月份最后一天的日期

原文链接:https://www.python100.com/html/FO4V925RU45O.html