如何获取月份总天数,实现倒计时剩余天数自动计算
核心实现思路
JS的Date对象自带日期容错特性,当你向构造函数传入的日期参数为0时,会自动返回对应月份上个月的最后一天,利用这个特性就可以快速获取指定月份的总天数,不需要手动判断大小月、闰年等边界情况。
代码实现
1. 封装获取指定月份总天数的方法
// 入参说明:year为4位年份,month遵循JS Date规范,0代表1月,11代表12月 function getMonthTotalDays(year, month) { return new Date(year, month + 1, 0).getDate(); }
2. 自动生成结束时间并计算剩余时长
对应你原有的手动指定结束时间的需求,自动生成当月最后一天指定时分秒的结束对象:
const now = new Date(); const currentYear = now.getFullYear(); const currentMonth = now.getMonth(); const currentDay = now.getDate(); // 当月总天数 const monthTotalDays = getMonthTotalDays(currentYear, currentMonth); // 当月剩余天数(按自然日计算,即示例中30-8的逻辑) const remainingNaturalDays = monthTotalDays - currentDay; // 自动生成当月最后一天13:00:12:12的结束时间对象,替代你手动写的固定日期 const end = new Date(currentYear, currentMonth, monthTotalDays, 13, 0, 12, 12); // 如果需要精确到时分秒的剩余时长,可通过时间戳计算 const remainingMs = end.getTime() - now.getTime(); const remainingDays = Math.floor(remainingMs / (1000 * 60 * 60 * 24)); const remainingHours = Math.floor((remainingMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const remainingMinutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60)); const remainingSeconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
注意事项
- 如果你传入的是日常使用的1-12格式的月份,需要先减1再传入方法,比如要获取2024年9月的总天数,调用方式为
getMonthTotalDays(2024, 8) - 方法会自动处理闰年2月的特殊情况,不需要额外加判断逻辑
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

