我正在尝试创建排序日期列表。我不能使用外部库,例如moment.js。它需要以年 - 月的方式格式化,范围为2年除以月。我做了几个月的清单,它适用于我,但我有多年的问题(在附加的例子中,它没有运作良好)。 您对如何改进此列表有任何想法或建议吗?
var today = new Date();
var months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var initalList = [];
var previousYear = today.getFullYear() -1;
var aMonth = today.getMonth();
for (var i=0; i<25; i++) {
initalList.push({month: months[aMonth], year: previousYear, myDate: previousYear + '-' + months[aMonth]});
if(i > 12) {
previousYear = today.getFullYear();
}
aMonth++;
if(aMonth > 11) {
aMonth = 0;
}
}
initalList.shift();
console.log(initalList)
&#13;
答案 0 :(得分:2)
您只需要减去月份,本机日期将完成您需要的操作。请参见下面的示例:
var dates = [];
var now = new Date();
var numberOfPastMonths = 24;
var year = now.getFullYear();
var month = now.getMonth();
//months quantity
for(var i = 0; i < numberOfPastMonths; i++){
//you only need to substract the months
dates.push(new Date(year, month - i, 1));
}
console.log(dates);
&#13;
答案 1 :(得分:1)
不确定您需要不同的解决方案,但我认为以下可以解决您的嵌套循环问题。
var today = new Date();
var result = [];
for (var i = 1; i >= 0; i--) {
for (var j = 1; j <= 12; j++) {
var yr = today.getFullYear() - i;
var mnth = ("0" + j).slice(-2);
result.push({
month: mnth,
year: yr,
myDate: yr + "-" + mnth
})
}
}
console.log(result);
&#13;