【问题标题】:convert month value to an integer in javascript, in order to use getMonth()+1?在javascript中将月份值转换为整数,以便使用getMonth()+1?
【发布时间】:2012-10-31 13:28:40
【问题描述】:

我想做类似这段代码的事情,但是日期不允许我这样做:当月份超过 11 时,警报会显示“undefined”,例如 12、13...

我想从一个月导航到另一个月,所以我需要执行getMonth()+1+2 之类的操作,即使当前月份是 12 月(这样,December+1 (11+1) 会给我January (0) )。您知道如何实现吗?

var m = mdate.getMonth();
    alert(nextMonth(m+3));

    function nextMonth(month){
        if (month>11) {
            if(month==12) month=0;
            if(month==13) month=1;
        } else {
            return month;
        }
    }

谢谢

【问题讨论】:

  • nextMonth 通常只返回月份。 “下”个月怎么样?
  • 我认为使用模数函数会更好。如果你有nextMonth(123)怎么办?

标签: javascript date integer monthcalendar


【解决方案1】:

使用取模运算符保持在范围内。

function nextMonth(month){
    return month % 12
}

【讨论】:

    【解决方案2】:

    你可以使用模块化划分:

    var m = 11;
    alert((m+1) % 12); // 0
    alert((m+2) % 12); // 1
    

    这不是一个好主意。 javascript 中的内置日期函数将为您处理。

    someDate.setMonth(someDate.getMonth() + m);
    

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 2021-03-03
      • 2013-03-08
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多