Search code examples
javascriptdateintegermonthcalendar

convert month value to an integer in javascript, in order to use getMonth()+1?


I wanted to do something like this code, but the date does not let me do it: the alert says "undefined" when the month is over 11, such as 12, 13...

I would like to navigate from a month to another, so i would need to do something like getMonth()+1 or +2, even if the current month is December (so that, December+1 (11+1) would give me January (0) ). Would you know how to achieve this?

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

Thanks


Solution

  • Use the modulus operator to stay within the bounds.

    function nextMonth(month){
        return month % 12
    }