How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?
Any help would be great :)
How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?
Any help would be great :)
Here's a function that accurately provides the number of months between 2 dates.
The default behavior only counts whole months, e.g. 3 months and 1 day will result in a difference of 3 months. You can prevent this by setting the
roundUpFractionalMonths
param astrue
, so a 3 month and 1 day difference will be returned as 4 months.The accepted answer above (T.J. Crowder's answer) isn't accurate, it returns wrong values sometimes.
For example,
monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))
returns0
which is obviously wrong. The correct difference is either 1 whole month or 2 months rounded-up.Here's the function I wrote:
The definition of "the number of months in the difference" is subject to a lot of interpretation. :-)
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):
(Note that month values in JavaScript start with 0 = January.)
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.
There are also some date and time libraries available for JavaScript that probably make this sort of thing easier.
If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.
This is an extended version of the answer https://stackoverflow.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).
This will cover the following;
To expand on @T.J.'s answer, if you're looking for simple months, rather than full calendar months, you could just check if d2's date is greater than or equal to than d1's. That is, if d2 is later in its month than d1 is in its month, then there is 1 more month. So you should be able to just do this:
This doesn't totally account for time issues (e.g. 3 March at 4:00pm and 3 April at 3:00pm), but it's more accurate and for just a couple lines of code.