本文介绍了获取两个日期之间的月份名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须有两个日期from
和to
.我想获取这两个日期之间的所有月份名称.
I have to two dates from
and to
. I want to get all of the month names between these two dates.
以下是我的代码
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);
}
以上代码可用于以下输入
above code works for following inputs
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'));
这篇关于获取两个日期之间的月份名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!