js 怎么计算出 两个日期之间相差多少月 比如:

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js 怎么计算出 两个日期之间相差多少月 比如:相关的知识,希望对你有一定的参考价值。

js 怎么计算出 两个日期之间相差多少月 比如:
“2011-05” 到 “2012-07” 相差多少月
并且 能得到 201105 201106 201107 ................这样的数据传入后端
同时得到 2011年5月 2011年6月 2011年 7月 .......................这样的数据传入后端

用js怎么处理这个时间差

参考技术A function monthDiff(d1, d2)
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;


monthDiff(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 15: December 2008, all of 2009, and Jan & Feb 2010

monthDiff(
new Date(2010, 0, 1), // January 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 1: February 2010 is the only full month between them

monthDiff(
new Date(2010, 1, 1), // February 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 0: There are no *full* months between them
参考技术B 
function getD(a,b)
var arrA = a.split("-"),
arrB = b.split("-"),
yearA = arrA[0],
yearB = arrB[0],
monthA = +arrA[1],
monthB = (yearB-(+yearA))*12+parseInt(arrB[1]),
rA = [],
rB = [];

do
do
rA.push(yearA+""+(monthA > 9 ? monthA : "0"+monthA));
rB.push(yearA+"年"+monthA+"月");
if(monthA == 12)
monthA=1;
monthB -= 12;
break;

while(monthB > monthA++)
while(yearB > yearA++)

return [rA,rB];


var c = getD("2011-05","2012-12");
alert(c)本回答被提问者采纳
参考技术C 有编程嘛!!!

以上是关于js 怎么计算出 两个日期之间相差多少月 比如:的主要内容,如果未能解决你的问题,请参考以下文章

请教下各位,js计算时间差怎么计算,计算出两时间差得年、月、日

在JAVA中如何算出两段时间相差的月数 ,

js怎么计算2个日期之间差多少天

java中如何计算出两个日期之间相差多少天

js根据年月计算出这个月有多少周

js 两个日期 相差多少年的计算