javascript怎么根据月判定有多少天

javascript怎么根据月判定有多少天,第1张

javascript怎么根据月判定有多少天

方法: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")

方法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)

【相关推荐:javascript学习教程

以上就是javascript怎么根据月判定有多少天的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/691213.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-21
下一篇 2022-04-21

发表评论

登录后才能评论

评论列表(0条)

保存