Here is a relatively simple algorithm for doing this.
fromdate should be before todate. If else indicate this and exit.
Seperateout the date, month and year parts of both dates (fromdate and todate)into 6 variables say date1, month1, year1, date2, month2 and year2.
yd=year2-year1
md=month2-month1
dd=date2-date1
You can notice the following observations.
1) yd will never be less than 0.
2) If yd=0, then month difference will not be less than zero.
3) if yd=0 and md=0, then dd is greater than zero.
if(yd>0) then
if(md>0) then
if(dd<0) then
md=md-1
dd=getlastdateofmonth(month2-1, year2)-date1+date2
end if
elseif(md=0) then
if(dd<0) then
yd=yd-1
md=md+11
dd=getlastdateofmonth(month2-1, year2)-date1+date2
end if
else
yd=yd-1
md=md+12
if(dd<0) then
md=md-1
dd=getlastdateofmonth(month2-1, year2)-date1+date2
end if
end if
else ' yd=0
if(dd<0) then
md=md-1
dd=getlastdateofmonth(month2-1, year2)-date1+date2
end if
end if
Where the function getlastdateofmonth gives the last date of given month. You can very easily write such a function. Please take into consideration whether year2 is leap year.
The output is
yd YEARS , md MONTHS and dd DAYS
For e.g. fromdate=14-11-03 and todate=24-09-05 gives
1 year, 10 months and 10 days
fromdate=24-09-03 and todate=14-11-03 gives
0 Yeras, 1 month and 21 days
|