0

Possible Duplicate:
How do I get the difference between two Dates in JavaScript?

I wanted to know how javascript can count the years and months between two dates. So for example between 26/10/2012 and 26/11/2013, there are 1 year and 1 month

I have tried it so but it is wrong :(

var diff =  (new Date(y, m - 1, d).getTime(2011,(11-1),26) - new Date(2012, (11-1), 26).getTime()) / 1000 / 60 / 60 / 24 / 30;
Community
  • 1
  • 1
DaLim
  • 19
  • 1
  • 5

1 Answers1

3

Assuming two dates, d1 and d2, where d2 is the greater of the two:

var month_diff = (d2.getFullYear() - d1.getFullYear()) * 12 + d2.getMonth() - d1.getMonth();
var years = floor(month_diff / 12);
var months = month_diff % 12;
alert(years + 'years and ' + months + ' months');

If your requirement is only to count full months you could add the following after the first line:

if (d2.getDate() - d1.getDate() < 0 && month_diff > 0) {
   month_diff--;
}
Mitch Satchwell
  • 4,770
  • 2
  • 24
  • 31