how to calculate number of months between two dates using javascript

• Oct 10, 2007, 02:52
rajeshwarreddyt
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.
• Oct 10, 2007, 03:48
gRoberts
• Oct 11, 2007, 07:27
temp304
• Oct 12, 2007, 03:37
trib4lmaniac
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--; }```
• Oct 12, 2007, 03:46
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);
• Oct 12, 2007, 05:37
gRoberts
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">     <head>         <title>Untitled Document</title>         <link rel="stylesheet" type="text/css" media="screen" />         <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;             }             window.onload = function() {                 alert(monthDiff(new Date(2007, 0, 1), new Date()));             }         </script>     </head>     <body>                     </body> </html>```
• Oct 12, 2007, 06:44
trib4lmaniac
Quote:

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.
• Oct 12, 2007, 07:02
mrhoo
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);