如何获得上个月(DECEMBER)的名字 - JQUERY

时间:2017-01-03 12:35:27

标签: javascript jquery

如何在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];
}

我在代码中尝试了一些不同的东西,但没有运气。

4 个答案:

答案 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;