如何在jQuery中获取上个月的名称?它不适用于 december 月。
var now = new Date();
var currentYear = (new Date).getFullYear();
var currentMonth = GetMonthName((new Date).getMonth());
var lastMonth = GetMonthName((now.getMonth() - 1));
function GetMonthName(monthNumber) {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[monthNumber];
}
我在代码中尝试了一些不同的东西,但没有运气。
答案 0 :(得分:2)
另一种方法:
function GetMonthName(monthNumber) {
var months = ['December', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[++monthNumber];
}
console.log(GetMonthName(-1));
console.log(GetMonthName(0));
console.log(GetMonthName(11));
或更简单:
function GetMonthName(monthNumber) {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[monthNumber] || 'December';
}
console.log(GetMonthName(-1));
console.log(GetMonthName(0));
console.log(GetMonthName(11));
或使用数组的slice方法:
function GetMonthName(monthNumber) {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months.slice(monthNumber)[0];
}
console.log(GetMonthName(-1));
console.log(GetMonthName(0));
console.log(GetMonthName(11));
答案 1 :(得分:1)
对于任何前一个月,这应该有效:
function GetMonthName(monthNumber) {
monthNumber = monthNumber < 0 ? 11 : monthNumber;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[monthNumber];
}
答案 2 :(得分:0)
您可以尝试使用上个月:jsfiddle.net/bharatsing/jc3gpwfn/
var now = new Date();
var currentYear = (new Date).getFullYear();
var currentMonth = GetMonthName((new Date).getMonth());
var newdate=new Date(now.setMonth(now.getMonth() - 1));
var lastMonth = GetMonthName((newdate.getMonth()));
alert(lastMonth);
function GetMonthName(monthNumber) {
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
return months[monthNumber];
}
答案 3 :(得分:0)
var lastMonth = GetMonthName((now.getMonth() - 1));
if(lastMonth < 0) lastMonth = 11;