JavaScript 中两个日期之间的月差 [英] Difference in Months between two dates in JavaScript
问题描述
如何计算 JavaScript 中两个 Date() 对象的差异,同时只返回差异的月数?
How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?
任何帮助都会很棒:)
推荐答案
相差月数"的定义有很多解释.:-)
The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)
您可以从 JavaScript 日期对象中获取年、月和日.根据您要查找的信息,您可以使用这些信息来计算两个时间点之间有多少个月.
You can get the year, month, and day of month from a JavaScript date object. Depending on what information you're looking for, you can use those to figure out how many months are between two points in time.
例如,即兴的:
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
function test(d1, d2) {
var diff = monthDiff(d1, d2);
console.log(
d1.toISOString().substring(0, 10),
"to",
d2.toISOString().substring(0, 10),
":",
diff
);
}
test(
new Date(2008, 10, 4), // November 4th, 2008
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 16
test(
new Date(2010, 0, 1), // January 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 2
test(
new Date(2010, 1, 1), // February 1st, 2010
new Date(2010, 2, 12) // March 12th, 2010
);
// Result: 1
(请注意 JavaScript 中的月份值以 0 = 一月开始.)
(Note that month values in JavaScript start with 0 = January.)
在上面包括小数月份要复杂得多,因为典型的二月份的三天比八月份的三天(〜9.677%)占该月的更多部分(~10.714%),当然即使是二月份也是一个移动的目标取决于它是否是闰年.
Including fractional months in the above is much more complicated, because three days in a typical February is a larger fraction of that month (~10.714%) than three days in August (~9.677%), and of course even February is a moving target depending on whether it's a leap year.
还有一些 日期和时间库可用于 JavaScript,这可能会使此类事情变得更容易.
There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.
注意:上面曾经有一个+1
,这里:
Note: There used to be a + 1
in the above, here:
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
// −−−−−−−−−−−−−−−−−−−−^^^^
months += d2.getMonth();
那是因为最初我说:
...这会找出两个日期之间有多少个整月,不计算部分月份(例如,不包括每个日期所在的月份).
...this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in).
我出于两个原因将其删除:
I've removed it for two reasons:
如果不计算部分月份,结果不是很多(大多数?)人想要的答案,所以我想我应该把它们分开.
Not counting partial months turns out not to be what many (most?) people coming to the answer want, so I thought I should separate them out.
即使按照那个定义,它也并不总是有效.:-D (对不起.)
It didn't always work even by that definition. :-D (Sorry.)
这篇关于JavaScript 中两个日期之间的月差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!