今日の日付から始まる次の12か月(両端を含む)のリストを生成するための次のコードがあります。
function DateUtilFunctions() {
var self = this;
var monthNames = new Array();
monthNames[0] = "January";
monthNames[1] = "February";
monthNames[2] = "March";
monthNames[3] = "April";
monthNames[4] = "May";
monthNames[5] = "June";
monthNames[6] = "July";
monthNames[7] = "August";
monthNames[8] = "September";
monthNames[9] = "October";
monthNames[10] = "November";
monthNames[11] = "December";
self.getNext12MonthNamesWithYear = function () {
var months = new Array();
var today = new Date(Date());
var loopDate = new Date();
loopDate.setTime(today.valueOf());
var todayPlus12Months = new Date(today.setMonth(today.getMonth() + 12));
while (loopDate.valueOf() < todayPlus12Months.valueOf()) {
alert(loopDate);
alert(loopDate.getMonth());
var month = monthNames[loopDate.getMonth()];
months.push(month + ' ' + loopDate.getFullYear());
loopDate.setMonth(loopDate.getMonth() + 1);
}
return months;
};
}
呼び出しの結果getNext12MonthNamesWithYear()
は次のとおりです。
- 「2012年5月」
- 「2012年7月」
- 「2012年8月」
- 「2012年5月」
- 「2012年7月」
- 「2012年8月」
- 「2012年9月」
- 「2012年10月」
- 「2012年11月」
- 「2012年12月」
- 「2013年1月」
- "2013年2月"
- 「2013年3月」
- "2013年4月"
- "2013年5月"
できる限り、リストの先頭は少し奇妙です。「6月」が欠落していることに加えて、「5月」、「7月」、「8月」が2回表示されます。
当然、私はここで非常に間違ったことをしています。誰かが私を助けてくれませんか?
編集:
micadelliのコメントに基づいて、私が使用したソリューションは次のとおりです。
function DateUtilFunctions() {
var self = this;
var monthNames = new Array();
monthNames[0] = "January";
monthNames[1] = "February";
monthNames[2] = "March";
monthNames[3] = "April";
monthNames[4] = "May";
monthNames[5] = "June";
monthNames[6] = "July";
monthNames[7] = "August";
monthNames[8] = "September";
monthNames[9] = "October";
monthNames[10] = "November";
monthNames[11] = "December";
self.getNext12MonthNamesWithYear = function () {
var months = new Array();
var today = new Date();
var tmpDate = new Date();
var tmpYear = tmpDate.getFullYear();
var tmpMonth = tmpDate.getMonth();
var monthLiteral;
for (var i = 0; i < 12; i++) {
tmpDate.setMonth(tmpMonth + i);
tmpDate.setFullYear(tmpYear);
monthLiteral = monthNames[tmpMonth];
months.push(monthLiteral + ' ' + tmpYear);
tmpYear = (tmpMonth == 11) ? tmpYear + 1 : tmpYear;
tmpMonth = (tmpMonth == 11) ? 0 : tmpMonth + 1;
}
return months;
};
}