【问题标题】:problem fetching number of days in a month in Javascript在Javascript中获取一个月中的天数的问题
【发布时间】:2023-03-24 19:37:01
【问题描述】:

我有一连串的年、月开始日和结束日选择元素.. 年和当然月都可用,但问题在于要从中选择所选月份的天数,作为开始日!

我在 JS 文件中使用它 days = new Date(2010, 4, 0).getDate(); // returns 29,应该是30!

问题出在哪里,我通过返回 30 的 php cal_days_in_month(0, 4, 2010) 确定了每个月的天数

提前致谢:)

【问题讨论】:

    标签: php javascript date calendar


    【解决方案1】:

    如果您只是接受日期是从 1 开始的,那么一个小技巧可以为您提供给定月份的天数:

    function getDaysForMonth(m,y){
      var datebase = new Date(y,m,1); //nb: month = zerobased
      datebase.setDate(datebase.getDate()-1);
      return datebase.getDate();
    }
    

    让我们把它当作一些 2 月的:

    var feb2000 = getDaysForMonth(2,2000); //=> 29
    var feb2004 = getDaysForMonth(2,2004); //=> 29
    var feb2008 = getDaysForMonth(2,2008); //=> 29
    var feb2010 = getDaysForMonth(2,2010); //=> 28
    

    你可以为它创建一个 Date.prototype 方法:

    Date.prototype.daysThisMonth = function(){
     var x = new Date(this.getFullYear(),this.getMonth()+1,1);
     x.setDate(x.getDate()-1);
     return x.getDate();
    };
    //usage
    var d1 = new Date('2010/2/23').daysThisMonth() //=> 28
    //nb new Date('2010/2/23') in your notation: new Date(2010,1,23)
    

    【讨论】:

    • 我不知道你在做什么,但是 new Date('2010/04/23').daysThisMonth() = 30 here;
    【解决方案2】:

    我使用date.js。它有许多方便的日期功能。

    【讨论】:

      【解决方案3】:

      在谷歌浏览器中它只输出 30:

      document.write(days = new Date(2010, 4, 0).getDate());

      【讨论】:

      • firefox 3.6.13 /w firebug 1.6: new Date(2010,4,0).getDate() = 30
      【解决方案4】:

      你的代码

      new Date(2010, 4, 0)
      

      ...不正确;它可能在某些实现中有效,但在其他实现中无效。 Date 构造函数需要年、月、日、小时、分钟和秒(除了yearmonth 之外的所有内容都是可选的,因为如果您使用单参数构造函数,它假定您给出毫秒-因为-The-Epoch 值),月份是从 0 开始的,但天是从 1 开始的(是的,真的——嘿,我没有设计它)。所以四月的第一天是new Date(2010, 3, 1)0 = 一月,1 = 二月,2 = 三月,3 = 四月)并且没有一个月中的日期0(根据部分规范的 15.9.1.5,范围是 1..31)。

      【讨论】:

      • 谢谢,但我并没有真正明白你的意思!:),这是我得到代码的地方:electrictoolbox.com/javascript-days-in-month
      • @Dewan:我的意思是new Date(2010, 4, 0) 是无效的并且可以返回任何东西。第三个值不能是0(根据规范,必须是131 包括在内),这意味着你得到你得到的任何东西并且不能信任它。
      【解决方案5】:

      确保您使用下个月作为参数,因为当天为 0 时它会向后移动:

      new Date(2012, 1, 0); //returns Jan not Feb
      

      如果这是您经常使用的东西,请创建一个函数

      function getDaysOfMonth(year, month){
         return new Date(year, month+1, 0).getDate()
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 2021-07-30
        相关资源
        最近更新 更多