Bad, bad, bad algorithm!

As everybody knows, time flies. The algorithm below was constructed to find out how fast. How many years, months, and days have passed since, for example, man landed on the moon?

Feed the algorithm 27 January 2010 and 16 July 1969 and it spits out 40y 6m -4d while the correct answer is 40y 6m 11d.

Can you fix it or, much better, make your own algorithm?

FUNCTION AGE

SET DATE TO DMY

M.ageYear=0

M.ageMonth=0

M.ageDays=0

CurrentBirthDate=GOMONTH(_bDate,(YEAR(_chkDate)-YEAR(_bDate))*12)

tmpDate=CurrentBirthDate

M.ageYear=(YEAR(_chkDate)-YEAR(_bDate))

IF CurrentBirthDate>_chkDate

M.ageYear=(YEAR(_chkDate)-YEAR(_bDate))-1

M.ageMonth=0

tmpDate=GOMONTH(CurrentBirthDate,-12)

ENDIF

DO WHILE tmpDate <= _chkdate

IF MONTH(CurrentBirthDate)=2

IF YEAR(_chkdate)=YEAR(CurrentBirthDate) AND MONTH(CurrentBirthDate)=MONTH(_chkdate)

tmpDate=CurrentBirthDate

EXIT

ELSE

M.ageMonth=M.ageMonth+1

tmpDate=GOMONTH(tmpDate,1)

ENDIF

ELSE

M.ageMonth=M.ageMonth+1

tmpDate=GOMONTH(tmpDate,1)

ENDIF

ENDDO

IF _chkDate < tmpDate

IF MONTH(tmpDate)=2 AND day(tmpDate)!=day(_chkDate)

M.ageMonth=M.ageMonth-1

_DateString1=”{^”+allt(STR(YEAR(tmpDate)))+”/”+allt(STR(MONTH(tmpDate)))+”/1}-1″

tmpDate=&_DateString1

ELSE

M.ageMonth=M.ageMonth-1

_DateString1=”{^”+allt(STR(YEAR(tmpDate)))+”/”+allt(STR(MONTH(tmpDate)))+”/1}-1″

tmpDate=GOMONTH(tmpDate,-1)

ENDIF

ENDIF

M.ageDays=_chkDate-tmpDate

RETURN ALLTRIM(STR(m.ageYear))+”y “+ALLTRIM(STR(m.ageMonth))+”m “+ALLTRIM(STR(m.ageDays)) + “d”

The algorithm is written in FoxPro 9 and was found on the Internet. Note that Gomonth() returns the date that is a specified number of months before or after a given date, while Year() returns the year from the specified date.

2 Responses to “Bad, bad, bad algorithm!”

  1. Michael Maguire Says:

    This is too complicated. Most languages have date/time constructs that deal with this elegantly.

    DateTime chkdate = new DateTime(2010,1,27);
    DateTime bdate = new DateTime(1969,7,16);

    Then just subtract one from the other and extract the year, month, and day from the resulting number.

  2. Jan Nordgreen Says:

    If the subtraction gives number of days then it is not trivial to subtract year, month, and day as the months do not all have 30 days.

Leave a Reply