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.
Days Between Two Dates script - http://javascriptbank.com/javascript/run-script-days-between-two-dates-script.html
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--;
}
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);
answer = c.getMonth();
i’ve had a little play and got this. It may need a little tweaking but seems to work.
<!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>
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.
September 15 is not a full month from October 12, though the getMonth() difference is 1.
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);
alert(Date.monthsDiff(d1,d2));