# Thread: how to calculate number of months between two dates using javascript

1. ## how to calculate number of months between two dates using javascript

Hi Folks,
I want to calculate number of months between two dates using javascript, can any one help me out to do this, its urgent.

2. Code JavaScript:
```var a = someDate;
var b = someOtherDate;

// Months between years.
var months = (b.getFullYear() - a.getFullYear()) * 12;

// Months between... months.
months += b.getMonth() - a.getMonth();

// Subtract one month if b's date is less that a's.
if (b.getDate() < a.getDate())
{
months--;
}```

3. You would need to tidy this up a little but theoretically all you need is:

var a = someDate;
var b = someOtherDate;

var c = Math.abs(a - b);

4. i've had a little play and got this. It may need a little tweaking but seems to work.

Code:
```<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Untitled Document</title>
<style type="text/css"></style>
<script type="text/javascript">
function monthDiff(start, end) {
var tempDate = new Date(start);
var monthCount = 0;
while((tempDate.getMonth()+''+tempDate.getFullYear()) != (end.getMonth()+''+end.getFullYear())) {
monthCount++;
tempDate.setMonth(tempDate.getMonth()+1);
}
return monthCount+1;
}
alert(monthDiff(new Date(2007, 0, 1), new Date()));
}
</script>
<body>

</body>
</html>```

5. Originally Posted by felgall
You would need to tidy this up a little but theoretically all you need is:

var a = someDate;
var b = someOtherDate;

var c = Math.abs(a - b);
I cannot see how that could work even with a bit of tidying.
For a start, getMonth() cannot return a number greater than 11, whereas there can by more than 11 months between two dates.

6. September 15 is not a full month from October 12, though the getMonth() difference is 1.

Code:
```Date.monthsDiff= function(day1,day2){
var d1= day1,d2= day2;
if(day1<day2){
d1= day2;
d2= day1;
}
var m= (d1.getFullYear()-d2.getFullYear())*12+(d1.getMonth()-d2.getMonth());
if(d1.getDate()<d2.getDate()) --m;
return m;
}```
//test case
var d1= new Date(2007,9,12);
var d2= new Date(2006,8,13);