使用 JavaScript 确定一个月中的天数的最佳方法是什么? [英] What is the best way to determine the number of days in a month with JavaScript?

查看:28
本文介绍了使用 JavaScript 确定一个月中的天数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用此功能,但我想知道获取它的最有效和最准确的方法是什么.

I've been using this function but I'd like to know what's the most efficient and accurate way to get it.

function daysInMonth(iMonth, iYear) {
   return 32 - new Date(iYear, iMonth, 32).getDate();
}

推荐答案

function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
  return new Date(year, month, 0).getDate();
}

console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.

第 0 天是上个月的最后一天.因为月份构造函数是基于 0 的,所以这很好用.有点小技巧,但这基本上就是你减去 32 所做的.

Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely. A bit of a hack, but that's basically what you're doing by subtracting 32.

查看更多:当月的天数

这篇关于使用 JavaScript 确定一个月中的天数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆