“差异中的月数”的定义要经过很多解释。:-)
您可以从JavaScript日期对象获取年,月和日。根据您要查找的信息,可以使用这些信息来计算两个时间点之间有多少个月。
例如,现成的,它找出两个日期之间有多少 整月 ,而不计算部分月份(例如,不包括每个日期所在的月份):
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
(请注意,JavaScript中的月份值以0 =一月开头。)
在上面包含小数月要复杂得多,因为典型的2月中的三天要占该月的一部分(?10.714%)比8月的三天(?9.677%)要大,当然,甚至2月也是一个移动的目标取决于是否是a年。
还有一些可用于JavaScript的日期和时间库可能会使这种事情变得更容易。