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

查看:111
本文介绍了用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) {
  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天全站免登陆