本文介绍了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.

例如, ,这会发现两个日期之间有多少个月,不包括部分月份(例如,不包括每个日期所在的月份):

For instance, off-the-cuff, this finds out how many full months lie between two dates, not counting partial months (e.g., excluding the month each date is in):

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 = 1月开始。)

(Note that month values in JavaScript start with 0 = January.)

在上述中包括小数月份要复杂得多,因为典型的二月份的三天是那个月(〜10.714%)比八月份的三天多(〜9.677%),当然甚至二月是一个移动目标,取决于是闰年。

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.

这篇关于JavaScript中的两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:48