代码之家  ›  专栏  ›  技术社区  ›  Chatu

使用JavaScript确定一个月的天数的最佳方法是什么?

  •  93
  • Chatu  · 技术社区  · 17 年前

    我一直在使用这个函数,但我想知道获得它的最有效和最准确的方法是什么。

    function daysInMonth(iMonth, iYear) {
       return 32 - new Date(iYear, iMonth, 32).getDate();
    }
    
    12 回复  |  直到 8 年前
        1
  •  218
  •   crg ali    4 年前

    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天是上个月的最后一天。因为month构造函数是基于0的,所以它工作得很好。有点像黑客,但这基本上就是减去32。

    Number of days in the current month

        2
  •  8
  •   Community Mohan Dere    9 年前

    一些答案(还有其他问题)有闰年问题或使用日期对象。虽然javascript Date object 涵盖了大约285616年(100000000天)在1970年1月1日左右,我厌倦了各种各样的意外日期 inconsistencies 跨不同的浏览器(最显著的是0到99年)。我也很好奇如何计算它。

    小的 对的 ( Proleptic Gregorian /天文/ISO 8601:2004(第4.3.2.1条),因此 year 0 存在并且是闰年和闰年 支持负年份
    它使用 short-circuit bitmask-modulo leapYear algorithm (对于js稍微修改)和常见的mod-8月算法。

    AD/BC 符号,公元前0年不存在:而是年份 1 BC 是闰年!
    若你们需要考虑BC符号,那个么只需先减去一年的年值(否则为正)!!(或从中减去年份) 1 以便进一步计算年份。)

    function daysInMonth(m, y){
      return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);
    }
    <!-- example for the snippet -->
    <input type="text" value="enter year" onblur="
      for( var r='', i=0, y=+this.value
         ; 12>i++
         ; r+= 'Month: ' + i + ' has ' + daysInMonth(i, y) + ' days<br>'
         );
      this.nextSibling.innerHTML=r;
    " /><div></div>

    注意,月份必须以1为基础!

    注意,这是一个不同的算法,然后我在我的 Javascript calculate the day of the year (1 - 366)

        3
  •  7
  •   Community Mohan Dere    9 年前

    如果您经常调用此函数,缓存该值以获得更好的性能可能会很有用。

    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
  •  4
  •   artem_p    10 年前

    具有 moment.js

    moment().daysInMonth(); // number of days in the current month
    moment("2012-02", "YYYY-MM").daysInMonth() // 29
    moment("2012-01", "YYYY-MM").daysInMonth() // 31
    
        5
  •  4
  •   Jaybeecave    4 年前

    为了消除混淆,我可能会使month字符串基于当前的0。

    function daysInMonth(month,year) {
        monthNum =  new Date(Date.parse(month +" 1,"+year)).getMonth()+1
        return new Date(year, monthNum, 0).getDate();
    }
    
    daysInMonth('feb', 2015)
    //28
    
    daysInMonth('feb', 2008)
    //29
    
        6
  •  2
  •   Masum Billah    7 年前

    来吧

    new Date(2019,2,0).getDate(); //28
    new Date(2020,2,0).getDate(); //29
    
        7
  •  2
  •   RASG    6 年前

    ES6语法

    const d = (y, m) => new Date(y, m, 0).getDate();
    

    console.log( d(2020, 2) );
    // 29
    
    console.log( d(2020, 6) );
    // 30
    
        8
  •  1
  •   Tony Li    12 年前
    function numberOfDays(iMonth, iYear) {
             var myDate = new Date(iYear, iMonth + 1, 1);  //find the fist day of next month
             var newDate = new Date(myDate - 1);  //find the last day
                return newDate.getDate();         //return # of days in this month
            }
    
        9
  •  1
  •   Yash    11 年前

    考虑闰年:

    function (year, month) {
        var isLeapYear = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
    
        return [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    }
    
        10
  •  1
  •   Tomas Langkaas    9 年前

    一行直接计算(无日期对象):

    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

    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);
    }
    
        11
  •  1
  •   mrplants    9 年前

    Date.prototype.getNumberOfDaysInMonth = function(monthOffset) {
        if (monthOffset !== undefined) {
            return new Date(this.getFullYear(), this.getMonth()+monthOffset, 0).getDate();
        } else {
            return new Date(this.getFullYear(), this.getMonth(), 0).getDate();
        }
    }
    

    var myDate = new Date();
    myDate.getNumberOfDaysInMonth(); // Returns 28, 29, 30, 31, etc. as necessary
    myDate.getNumberOfDaysInMonth(); // BONUS: This also tells you the number of days in past/future months!
    
        12
  •  1
  •   ADyson    8 年前

    在一行中:

    // month is 1-12
    function getDaysInMonth(year, month){
        return month == 2 ? 28 + (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : 1):0) : 31 - (month - 1) % 7 % 2;
    }
    
        13
  •  1
  •   Syed    6 年前

    与所选答案相比,可能有点过头了:),但这里是:

    function getDayCountOfMonth(year, month) {
      if (month === 3 || month === 5 || month === 8 || month === 10) {
        return 30;
      }
    
      if (month === 1) {
        if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
          return 29;
        } else {
          return 28;
        }
      }
    
      return 31;
    };
    
    console.log(getDayCountOfMonth(2020, 1));

    我在这里找到了上面的代码: https://github.com/ElemeFE/element/blob/dev/src/utils/date-util.js

    function isLeapYear(year) { 
      return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); 
    };
    
    const getDaysInMonth = function (year, month) {
      return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
    };
    
    console.log(getDaysInMonth(2020, 1));

    我在这里找到了上面的代码: https://github.com/datejs/Datejs/blob/master/src/core.js

        14
  •  1
  •   Sanka Sanjeeva    6 年前

    如果要传递日期变量,这可能会有所帮助

    const getDaysInMonth = date =>
      new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
    
    daysInThisMonth = getDaysInMonth(new Date());
    
    console.log(daysInThisMonth);
        15
  •  0
  •   Greg Herbowicz    5 年前

    一行,不使用日期对象:

    const countDays = (month, year) => 30 + (month === 2 ? (year % 4 === 0 && 1) - 2 : (month + Number(month > 7)) % 2);
    

    返回:

    countDays(11,2020) // 30
    countDays(2,2020) // 29
    countDays(2,2021) // 28
    
        16
  •  0
  •   crg ali    4 年前

    天数 本月

    let nbOfDaysInCurrentMonth = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 0)).getDate()
    
    console.log(nbOfDaysInCurrentMonth)
        17
  •  -1
  •   kmiklas    8 年前

    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;
    },
    
    推荐文章