如何根据月份判断JavaScript中该月具体有多少天?

2026-03-31 14:531阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计394个文字,预计阅读时间需要2分钟。

如何根据月份判断JavaScript中该月具体有多少天?

方法:1、使用new Date(year, month, 0)语句根据指定年月创建日期对象;2、使用日期对象.getDate()语句处理日期对象,返回指定月份的最后一天,即可知道指定月有多少天。

方法:1、使用“new Date(year, month,0)”语句根据指定年份和月份来创建日期对象;2、使用“日期对象.getDate()”语句处理日期对象,返回指定月份的最后一天,即可知道指定月份有多少天。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript根据月判定有多少天的方法

要想得到某月有多少天,只需要获取到当月最后一天的日期就行了

方法1:

灵活调用 setMonth(),getMonth(),setDate(),getDate(),计算出所需日期

实现代码:

function getMonthLength(date) { let d = new Date(date); // 将日期设置为下月一号 d.setMonth(d.getMonth()+1); d.setDate('1'); // 获取本月最后一天 d.setDate(d.getDate()-1); return d.getDate(); }

检测一下:

getMonthLength("2020-02-1") getMonthLength("2021-02-1") getMonthLength("2022-02-1") getMonthLength("2022-03-1")

如何根据月份判断JavaScript中该月具体有多少天?

方法2:

原来还有更简单的办法:直接调用getDate()

function getMonthLength(year,month) { return new Date(year, month,0).getDate(); }

检测一下:

getMonthLength(2020,02) getMonthLength(2021,02) getMonthLength(2022,02) getMonthLength(2022,03) getMonthLength(2022,04)

本文共计394个文字,预计阅读时间需要2分钟。

如何根据月份判断JavaScript中该月具体有多少天?

方法:1、使用new Date(year, month, 0)语句根据指定年月创建日期对象;2、使用日期对象.getDate()语句处理日期对象,返回指定月份的最后一天,即可知道指定月有多少天。

方法:1、使用“new Date(year, month,0)”语句根据指定年份和月份来创建日期对象;2、使用“日期对象.getDate()”语句处理日期对象,返回指定月份的最后一天,即可知道指定月份有多少天。

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

javascript根据月判定有多少天的方法

要想得到某月有多少天,只需要获取到当月最后一天的日期就行了

方法1:

灵活调用 setMonth(),getMonth(),setDate(),getDate(),计算出所需日期

实现代码:

function getMonthLength(date) { let d = new Date(date); // 将日期设置为下月一号 d.setMonth(d.getMonth()+1); d.setDate('1'); // 获取本月最后一天 d.setDate(d.getDate()-1); return d.getDate(); }

检测一下:

getMonthLength("2020-02-1") getMonthLength("2021-02-1") getMonthLength("2022-02-1") getMonthLength("2022-03-1")

如何根据月份判断JavaScript中该月具体有多少天?

方法2:

原来还有更简单的办法:直接调用getDate()

function getMonthLength(year,month) { return new Date(year, month,0).getDate(); }

检测一下:

getMonthLength(2020,02) getMonthLength(2021,02) getMonthLength(2022,02) getMonthLength(2022,03) getMonthLength(2022,04)