Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript month difference

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
like image 645
Tom Gullen Avatar asked Nov 30 '10 10:11

Tom Gullen


3 Answers

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.

like image 172
Tom Gullen Avatar answered Oct 01 '22 16:10

Tom Gullen


[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)
like image 43
KooiInc Avatar answered Oct 01 '22 15:10

KooiInc


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;

like image 34
Marina Avatar answered Oct 01 '22 16:10

Marina