What is the best way to determine the number of da

2019-01-01 10:14发布

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();
}

12条回答
墨雨无痕
2楼-- · 2019-01-01 10:48

With moment.js you can use daysInMonth() method:

moment().daysInMonth(); // number of days in the current month
moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31
查看更多
公子世无双
3楼-- · 2019-01-01 10:51

If you call this function often, it may be useful to cache the value for better performance.

Here is caching version of FlySwat's answer:

var daysInMonth = (function() {
    var cache = {};
    return function(month, year) {
        var entry = year + '-' + month;

        if (cache[entry]) return cache[entry];

        return cache[entry] = new Date(year, month, 0).getDate();
    }
})();
查看更多
浪荡孟婆
4楼-- · 2019-01-01 10:53

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.

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.

查看更多
时光乱了年华
5楼-- · 2019-01-01 10:53

Here is goes

new Date(2019,2,0).getDate(); //28
new Date(2020,2,0).getDate(); //29
查看更多
千与千寻千般痛.
6楼-- · 2019-01-01 10:57

One-liner direct computation (no Date object):

function daysInMonth(m, y) {//m is 1-based, feb = 2
   return 31 - (--m ^ 1? m % 7 & 1:  y & 3? 3: y % 25? 2: y & 15? 3: 2);
}

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

Variation with 0-based months:

function daysInMonth(m, y) {//m is 0-based, feb = 1
   return 31 - (m ^ 1? m % 7 & 1:  y & 3? 3: y % 25? 2: y & 15? 3: 2);
}
查看更多
刘海飞了
7楼-- · 2019-01-01 10:58

Perhaps not the most elegant solution, but easy to understand and maintain; and, it's battle-tested.

function daysInMonth(month, year) {
    var days;
    switch (month) {
        case 1: // Feb, our problem child
            var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
            days = leapYear ? 29 : 28;
            break;
        case 3: case 5: case 8: case 10: 
            days = 30;
            break;
        default: 
            days = 31;
        }
    return days;
},
查看更多
登录 后发表回答