View Full Version : Calculate No. of month based on start date and end date ?
12-06-2006, 04:35 AM
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.
12-06-2006, 11:09 AM
this shoud do the trick.
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
alert("the difference between "+startdate+" and "+enddate+"
is:\n"+yeardiff+" year(s), "+monthdiff+" month(s), "+daydiff+" day(s)");
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.
Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.