首页 > 解决方案 > Get the previous month name based on a supplied month name using JavaScript

问题描述

I'm trying to find the previous month name from a given month name. What is the best way of achieving this? Instead of passing current date month index, I need to pass the user's selected month name and get last month name.

For example:

  1. If the user selects "January" as month name, it needs to return "December"
  2. If the user selects "February" as month name, it needs to return "January"

Below is the sample code I am trying.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the name of this month.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var month = new Array();
  month[0] = "January";
  month[1] = "February";
  month[2] = "March";
  month[3] = "April";
  month[4] = "May";
  month[5] = "June";
  month[6] = "July";
  month[7] = "August";
  month[8] = "September";
  month[9] = "October";
  month[10] = "November";
  month[11] = "December";

  var d = new Date();
  var n = month[d.getMonth()-1];
  document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

标签: javascriptdate

解决方案


Just uses an array of month names. Lookup index and -1. || is for if 0 use 12, so January wraps around to December.

var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

function getLastMonth(month){return months[(months.indexOf(month) + 12 - 1) % 12]}

console.log(
  getLastMonth('January'),
  getLastMonth('November'),
  getLastMonth('December')
)


推荐阅读