我必须有两个日期 from
和 to
。我想获得这两个日期之间的所有月份名称。
以下是我的代码
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var arr = monthNames.slice(datFrom.getMonth(), datTo.getMonth() + 1);
}
上面的代码适用于以下输入
diff('September 2013', 'December 2013');
但它不适用于此
diff('September 2013', 'February 2014');
我怎样才能让它工作?
最佳答案
我的更好:http://jsfiddle.net/kS73f/8/
var monthNames = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
function diff(from, to) {
var arr = [];
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var fromYear = datFrom.getFullYear();
var toYear = datTo.getFullYear();
var diffYear = (12 * (toYear - fromYear)) + datTo.getMonth();
for (var i = datFrom.getMonth(); i <= diffYear; i++) {
arr.push(monthNames[i%12] + " " + Math.floor(fromYear+(i/12)));
}
return arr;
}
console.log(diff('September 2013', 'March 2014'));
关于javascript - 获取两个日期之间的月份名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21441830/