gpt4 book ai didi

javascript - JavaScript 中两个日期之间的月差

转载 作者:IT王子 更新时间:2023-10-29 02:39:23 26 4
gpt4 key购买 nike

我如何计算出 JavaScript 中两个 Date() 对象的差异,同时只返回差异中的月数?

任何帮助都会很棒 :)

最佳答案

“差月数”的定义有很多解释。 :-)

您可以从 JavaScript 日期对象中获取年月日。根据您要查找的信息,您可以使用这些信息来计算两个时间点之间相隔多少个月。

例如,即兴表演:

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 = January 开头。)

在上面包含小数月份要复杂得多,因为典型的 2 月的三天占该月的比例 (~10.714%) 比 8 月的三天 (~9.677%) 大,当然即使是 2 月也是移动目标取决于是否是闰年。

还有一些date and time libraries可用于 JavaScript,这可能会使这类事情变得更容易。


注意:上面曾经有一个+1,这里:

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).

我删除它有两个原因:

  1. 事实证明,不计算部分月份并不是许多(大多数?)来回答这个问题的人想要的,所以我认为我应该将它们分开。

  2. 即使按照那个定义,它也不总是有效。 :-D(抱歉。)

关于javascript - JavaScript 中两个日期之间的月差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2536379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com