javascript - 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:
- If the user selects "January" as month name, it needs to return "December"
- 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>
解决方案
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')
)
推荐阅读
- android - 对话框弹出并返回活动
- visual-studio-code - VS代码可以改变额外“结束”的颜色吗?
- node.js - 使用 nodejs 应用程序读取打字稿文件
- docker - 在多组织多主机环境中运行 Hyperledger Composer
- apache-spark - Spark中的表数据存储在哪里?
- php - 未定义变量:标记
- javascript - JSHint 引用外部作用域
- wordpress - meta_box_cb 函数下拉菜单在保存后创建另一个术语
- java - 如何在不使用 Java 泛型的情况下解决对 compareTo(T) 的未经检查的调用
- docker - 未发布的端口