JavaScript 计算指定月份有多少天

时间:2024-08-23 20:05:32

用 js 画工作日历的时候,需要用 js 计算指定月份一共有多少天

在网上找了些方法,都比较繁琐,后来灵机一动,想到一个偷懒的办法,分享一下

一、原理分析

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

围绕这一思路,灵活调用 setMonth(),getMonth(),setDate(),getDate(),计算出所需日期

二、代码实现

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

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQsAAAAyCAIAAADENWnUAAAG+klEQVR4nO2csW/TThTH81cghk79B5B+YuyKgI2OP7F1ATYvqFMXZ/KUIWL5/SRYmg4nUSYWp0UKosZCQpUQ+jWpU2QBalQpTuuoOEVp7N/w4PS4810uroFUvI9uIOfLu7v4fe+9O5tWspMTKlSoqEol29ujQoWKqlQygiDUkEIIQgcphCB0kEIIQgcphCB0kEIIQgcphCB0kEIuJb7vO47zu0dx+YiiyLKsKIrMv6JUyGg08jxvNBqVMbAi+L6/uLjo+z58ZIzhj6UQRdHy8nKuTd/3l5eXZ/opy4IxZllWkiSqBr7vLy0tBUGAKyfJl/0H9/cf3J8kX3jluN9/d/uWd/WKd/VKWLVx+9jbgXrv6pXY25Ev4fa4MZS31/9KOh39RFRdHG00zI3g2cntuSl5gkmn8/b6X0cbDcHU1J9XQKmQly9f1ut1xth4PDa0VZhcTwWF8JXScZyLKCS3i9+ukNy7pb+FmjGHVVtQSFi1wTVBKtxdkk7n3a2b4G2xt4M9L6zaB6sP9x/cFxwOE3s7727fGvf7mqmpukg6nYPVhzDIo43GVDvc1OG//wgKOdpo8PkKE8yt+WYtSSzLMo/ASoUMh8OnT5+CSE5PTw3NFSP3roOjQEyMoshxnLW1NcZYiV1cRoVoroZVW+PW2J9wS1ie4WPs7RxtNHCNDFyVPU8zGJVBcGIhgsndhVV73O8LSs7tQl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CDymEIHSQQghCBymEIHSQQghCBymEIHSQQghCBymEIHRMV8jXr19/wTgIYj6ZopA4jlut1snJibnFQf/87s3uQmV3obJbs3v40ub6AOrlSwQxn+gUEkVRq9VyXffDhw/mFmt2782r0+y7VDbXB1C/uT5YvfdxlKTyJYKYW/IVkqZpHMfb29uzykMAq6Jm93jcGCXp6r2PpBBi/slXyOHh4fb2drPZDMMwTdMsy4bD4cHBwdnZ2UzWsUK67bMb1/ZAJJvrg7s3u4P++YXHTxA/lxyFxHG8tbXlum632+WVr1+/dl13f3/f3LScSkHoWKjsctkQxJyTo5DJZPL+/XvXdVut1nA4hMpPnz55nmf4J7OAmt3DgQIEU7N7oJMb1/a67dkiEkH8evKzrPPz83a73Ww2W63WYFBkt1Cze4IGanaPhw4QCR1nEfOP8iwrTdN2u+26ruu6fbO/isfZXB8I8pAlgTfuBDG36E570zQNw7DZbH7+/Nnc4ptXpwuVXTjwxeDdOeza6SyLmH+mP1Of6T/14seFvHC11OweryR5EJcCei+LIHSQQghCBymEIHSQQghCBymEIHSQQghCR+WEIAg1/wM4m8BYuCp35AAAAABJRU5ErkJggg==" alt="" />

三、脸有点疼

发文还不到一小时,就被一位仁兄打脸了

原来还有更简单的办法:

new Date(year, month, ).getDate()

使用 new Date() 创建时间对象时,如果 date 传入 0,就能直接通过 getDate() 获取到最后一天的日期

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQ8AAAAuCAIAAAC5ygtOAAAHrklEQVR4nO2cv28aWRDH+QPyH8SVu1T+B5DuGp9bO1UuqeLGSkdzcuWGq0hxREK64qREsUR0p42w06CcFrvAIGdFY8VCggT8IzEyFmGx4chiy3j3ipFH47dvdx8EYiLNRxTx7nv7fux838yb3WzIYRhGjdBtd4BhfhhYLQyjCquFYVRhtQyAZVkrKyuVSuW2O/Kd0DRN07Tb7sXYMQwjFovhn6ZpRiIR0zTdJZXU0uv1tre3e73eyDo4IiqVSjgcnr6GjnnkWJYViUSEJuLRk7uh93dD7x/O7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