How do I calculate difference in months in Javascript?
Please note there are similar questions such as: What's the best way to calculate date difference in Javascript
But these are based around MS difference, when some months have different number of days than others!
Any easy way to calculate month difference between 2 dates?
Just to be clear, I need to know how many months the dates span, for example:
Jan 29th 2010, and Feb 1st 2010 = 2 months
Jan 1st 2010, and Jan 2nd 2010 = 1 month
Feb 14th 2010, Feb 1st 2011 = 13 months
Feb 1st 2010, March 30th 2011 = 14 months
DisplayTo.getMonth() - DisplayFrom.getMonth() + (12 * (DisplayTo.getFullYear() - DisplayFrom.getFullYear())));
getMonth minus getMonth gives you the month difference between the dates two months.
We then multiply 12 by the number of years difference and add this to the result giving us the full month span.
[edit] Based on comment, I stand corrected. Using the accepted answer I'd use somethng like:
var datefrom = new Date('2001/03/15')
,dateto = new Date('2011/07/21')
,nocando = datefrom<dateto ? null : 'datefrom > dateto!'
,diffM = nocando ||
dateto.getMonth() - datefrom.getMonth()
+ (12 * (dateto.getFullYear() - datefrom.getFullYear()))
,diffY = nocando || Math.floor(diffM/12)
,diffD = dateto.getDate()-datefrom.getDate()
,diffYM = nocando ||
(diffY>0 ? ' Year(s) ' : '')
+ diffM%12+' Month(s) '+(diffD>0? (diffD+' day(s)') : '') ;
console.log(diffYM); //=> 10 Year(s) 4 Month(s) 6 day(s)
I found the following on the website http://ditio.net/2010/05/02/javascript-date-difference-calculation/:
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
}
In your case, since you want to include all months in the date span, I would just modify the above code by adding 1 to it: return (d2M+12*d2Y)-(d1M+12*d1Y) + 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With