我正在使用JavaScript,尝试填写条形图。图表的最后一行是当前月份(2014年11月撰写时,如果使用JavaScript的Date(),则为10).getMonth()方法)。它开始计算在上一年的下个月(2013年12月,如果使用getMonth(),则计算为11)。
我的问题:从当前时间之前的11个月开始,12个月的最有效方式是什么?
我的首选输出是:
答案 0 :(得分:2)
您可以使用for循环并从当前日期中减去月份。就像下面所做的那样:
var dateObj = new Date();
var dateStrings = [];
var dateFormatOptions = {
month: 'long',
year: 'numeric'
};
for (var i = 0; i < 12; ++i) {
dateStrings.unshift(dateObj.toLocaleString('en-US', dateFormatOptions));
dateObj.setMonth(dateObj.getMonth() - 1);
}
document.getElementById("output").innerHTML = dateStrings.join("\n");
&#13;
<pre id="output"></pre>
&#13;
此代码将创建一个包含所需日期字符串的数组。
答案 1 :(得分:2)
可能的解决方案:
var date = new Date();
var dates = [];
var i, len;
for (i = 0, len = 12; i < len; i++) {
date.setMonth(date.getMonth() - 1);
dates.unshift(date.toLocaleString('en-us', {
month: 'long',
year: 'numeric'
}));
}
答案 2 :(得分:0)
像这样:
var months = [ "January"
, "February"
, "March"
, "April"
, "May"
, "June"
, "July"
, "August"
, "September"
, "October"
, "November"
, "December"
];
var now = new Date;
var month = now.getMonth() + 1;
var year = now.getFullYear() - 1;
if (month === 12) {
month = 0;
year++;
}
for (var i = 0; i < 12; i++) {
console.log(months[month++] + " " + year);
if (month === 12) {
month = 0;
year++;
}
}
答案 3 :(得分:0)
我只是使用for循环并在它们溢出时减去年份(并设置日期):
var date = new Date();
var currentMonth = date.getMonth();
var currentYear = date.getFullYear();
console.log(currentYear)
var month = ["January","February","March","April","May","June","July",
"August","September","October","November","December"];
var myArray = [];
for(var i = 0; i < 12; i++){
if(currentMonth == - 1){
currentMonth = 11;
date.setFullYear(parseInt(currentYear) - 1);
currentYear = date.getFullYear();
}
myArray.push(month[currentMonth]+" "+currentYear);
currentMonth--;
}
alert(myArray);