PDA

View Full Version : Calculate No. of month based on start date and end date ?

ntc2000
12-06-2006, 04:35 AM
Hi,

How can I calculate the number of month based on given start date and end date?

Let said, the start date and end date is based on yyyyMMdd,
End date = 20060312 End Date = 20060215
Start date = 20060111 or Start Date = 20051212

Number of month = 3 month(ceiling it)

i can get the number of day and number of weeks, but i m stuck in number of month coz it's due to 28,29,30,31 days and leap year.

Any Solution??? Help... I am new in javascript....

Thank...

brandonH
12-06-2006, 11:09 AM
this shoud do the trick.

<html>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">

<script LANGUAGE="javascript">
startdate=new Date();
enddate=new Date();
startdate.setFullYear(2002,0,12);
enddate.setFullYear(2006,11,15);
st=startdate.valueOf();
en=enddate.valueOf();
diff=en-st-(-0);
diffdate=new Date();
diffdate.setTime(diff);
yeardiff=enddate.getFullYear()-startdate.getFullYear();
monthdiff=diffdate.getMonth();
daydiff=enddate.getDate()-startdate.getDate();

alert("the difference between "+startdate+" and "+enddate+"
is:\n"+yeardiff+" year(s), "+monthdiff+" month(s), "+daydiff+" day(s)");

</script>

<body>
</body>
</html>

what i did was take the raw value of the two different dates ( .valueOf() )
and subtract the start date from the end date. what is left is a string of numbers that you can then create a new date from using .setTime(). this creates a whole new date. then we grab the value of the month in that date and it gives os the total number of months difference. note though, the year and day values of this new date are not valid for difference, only the month value is. then we figure out the difference in years by simply subtracting the start year from the end year, and do the same for the days. hope this explains it. if you are confused, just let me know and i will try to further explain it.

note: notice when I used the .setFullYear(), it has the actual year number, month, actual day. the one value in there different then the others is the month value, january is actually 0 and december is 11. you would thing january would be 1 and december would be 12, but with scripting, counting starts with 0.