【问题标题】:Javascript: calculate number of days in month for a given yearJavascript:计算给定年份的月份天数
【发布时间】:2011-06-20 09:31:32
【问题描述】:

我有一个 HTML 页面,其中包含月、日和年的 3 个下拉菜单,我想知道是否有办法根据月和年正确填充月下拉菜单。

我以前没有在客户端这样做过,但看起来很多控件(如 jQuery DatePicker)都在幕后执行此操作。

【问题讨论】:

标签: javascript date datepicker drop-down-menu leap-year


【解决方案1】:

据我所知,没有(整洁的)内置函数。我写过一次:

// note that month is 0-based, like in the Date object. Adjust if necessary.
function getNumberOfDays(year, month) {
    var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
    return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}

【讨论】:

  • 如何在数组中包含三元语句真是太棒了!不错!
  • 这应该是答案!太棒了!
【解决方案2】:

你可以玩日期对象:

var monthStart = new Date(year, month, 1);
var monthEnd = new Date(year, month + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24)

Date 对象的算术给出毫秒数。

这甚至适用于 12 月; Date 构造函数通过环绕处理超出范围的参数。

注意month 是从零开始的(它必须在011 之间)

【讨论】:

  • 这太棒了.. 它甚至适用于闰年。我试过 2/2012。谢谢!
  • 我将其包装为var DaysInMonth = function(year, month) { /* SLAK's code here */; return monthLength;};,并进一步添加了一个原型方法到日期Date.prototype.daysInMonth = function() { var mlen=DaysInMonth(this.getFullYear(), this.getMonth()); return mlen; };,以便我可以调用(new DateTime(2000, 1)).daysInMonth();
  • 2014 年 3 月由于某种原因返回 30.958333333333332。
  • 为避免使用小数,请将Math.round 添加到monthLength:monthLength = Math.round( (monthEnd - monthStart) / (1000 * 60 * 60 * 24) );
  • 由于夏令时,有些月份会多出 1 小时或少 1 小时。等式的(1000 * 60 * 60 * 24) 部分不考虑这种差异。四舍五入会有所帮助。
【解决方案3】:

从另一个帖子复制:Get number days in a specified month using javascript?

//Month is 1 based
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}

//July
daysInMonth(7,2009); //31
//February
daysInMonth(2,2009); //28
daysInMonth(2,2008); //29

感谢@c_harm,非常棒的解决方案

【讨论】:

    【解决方案4】:
    Date.prototype.daysinMonth: function(){
        var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
        return d.getDate();
    }
    
    function daysinMonthfromInput(month,year){
        return (new Date(year,month-1,1)).daysinMonth();
    }
    
    alert(daysinMonthfromInput(2,2011));
    

    【讨论】:

      【解决方案5】:

      这是一个班轮。 假设您说一月 = 1,二月 = 2 等..(正常) 这是闰年的例子:

      var y = 2012;
      var m = 2;
      var daysInMonth = new Date(y,m,1,-1).getDate();
      

      【讨论】:

        【解决方案6】:

        我在我当前的项目中使用这种方法,发现我需要纠正舍入错误。因此,我不得不在我的代码中使用monthLength,而不是使用它:

        monthLength.toFixed(0)
        

        例如,如果我有一个存储文本日期字段的对象,它可能如下所示:

        obj.month = theMonths[mm - 1] + " " + monthLength.toFixed(0) + ", " + obj.year;
        

        【讨论】:

          【解决方案7】:

          你可以实际使用这个:

          var curdate = new Date(); DaysMonth = 32 - 新日期(curdate.getYear(), curdate.getMonth(), 32).getDate();

          ;)

          【讨论】:

            【解决方案8】:

            这可能是对@MattiVirkkunen 给出的答案的改进:

            如果您有兴趣从该计算中榨取每一盎司的效率,您应该把它翻过来,首先处理所有“不是二月”的情况,这样可以避免当月份不是二月时进行闰年计算(时间的 11/12) .您也可以内联编码,避免昂贵的函数链接。

            month!=2 ? [31,28,31,30,31,30,31,31,30,31,30,31][month]
                     : (month%4!=0 ? 28 : (month%100!-0 : 29 (month%400!=0 ? 28 : 29)));
            

            【讨论】:

              【解决方案9】:
              Date.prototype.daysinMonth= function(){
              var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
              return d.getDate();
              };
              
              function daysinMonthfromInput  (month, year) {
                   return (new Date(year, month - 1, 1)).daysinMonth();
              };
              function fillallday (elem, month, year) {
                   var options = null;
                   var elementExists = document.getElementById(elem);
              
                   if (elementExists != null) {
              
                       this.removeOptions(elementExists);
                       var opt = document.createElement('option');
                       opt.value = "";
                       opt.innerHTML = "---Day---";
                       elementExists.appendChild(opt);
                       if (month != "") {
                           if (typeof (year) === "undefined") {
                               year = new Date().getFullYear();
                           }
                           if (year == "") {
                               year = new Date().getFullYear();
                           }
                           var days = daysinMonthfromInput(month, year);
                           for (var i = 1; i <= days; i++) {
                               var opt = document.createElement('option');
                               opt.value = i;
                               opt.innerHTML = i;
                               elementExists.appendChild(opt);
                           }
                       }
                   }
              
               }
              

              【讨论】:

              • 这个问题已经被正确回答了 - 这个答案增加了原始答案没有的什么?
              猜你喜欢
              • 1970-01-01
              • 2016-09-02
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-02-14
              • 1970-01-01
              • 2020-06-19
              • 1970-01-01
              相关资源
              最近更新 更多