I want to display a p tag with the next month, for example now is December But the p tag should be display January, If we in Jan the p tag should be display Febrary. What I have until now is this.
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const d = new Date();
let name = month[d.getMonth()];
document.getElementById("currentmonth").innerHTML = name;
<!DOCTYPE html>
<html>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>
</body>
</html>
CodePudding user response:
Simply take a variable and add one to the getMonth()
value and if it is greater than 11 then change it to 0.
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const d = new Date();
let name = month[d.getMonth()];
var x = d.getMonth() 1;
if(x>11)
x=0
document.getElementById("currentmonth").innerHTML = name;
document.getElementById("nextmonth").innerHTML = month[x];
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>
</body>
</html>
CodePudding user response:
You have to use setMonth to set the next month on the d variable.
d.setMonth(Month 1)
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
let Month = 11
const d = new Date();
d.setMonth(Month 1)
let name = month[d.getMonth()];
document.getElementById("currentmonth").innerHTML = name;
<!DOCTYPE html>
<html>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>
</body>
</html>
CodePudding user response:
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const d = new Date();
let name = month[d.getMonth()];
let nextMonth = month[(d.getMonth() 1)]
document.getElementById("currentmonth").innerHTML = name;
document.getElementById("nextmonth").innerHTML = nextMonth;
<!DOCTYPE html>
<html>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>
</body>
</html>
CodePudding user response:
If the order of the months is according to the real month indexes, you can do it as follows.
and i guess you forgot set value nextMonth
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
const d = new Date();
let name = month[d.getMonth()];
let next = month[(new Date().getMonth() 1)];
document.getElementById("currentmonth").innerHTML = `Current: ${name}`;
document.getElementById("nextmonth").innerHTML = `Next: ${next}`;
<!DOCTYPE html>
<html>
<body>
<p id="currentmonth"></p>
<p id="nextmonth"></p>
</body>
</html>