convert month value to an integer in javascript, in order to use getMonth()+1?
-
23-07-2021 - |
Frage
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
Lösung
Use the modulus operator to stay within the bounds.
function nextMonth(month){
return month % 12
}
Andere Tipps
You could use modular division:
var m = 11;
alert((m+1) % 12); // 0
alert((m+2) % 12); // 1
This is not a very good idea. The built in Date functions in javascript will handle this for you.
someDate.setMonth(someDate.getMonth() + m);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow