Age calculation algorithm

CA50

Skilled
Hi friends, currently i am developing a .NET app which requires the age of a person.

It will be like this :

- user enters the date-of-birth

- the age is automatically calculated till today.

Age format must be xx-years, xx -months, xx-days

Till now i have developed this algo, but if the age is less then 1 year (365 days), then bugs pops up
<


Here are the codes in C#



Code:
try

   {

		DateTime todays_date, date_of_birth;

		todays_date = DateTime.Today;

		//Date of Birth is accepted via user input at the date_time_picker

		date_of_birth = dtpTaxCalcForOthers_DOB.Value;

		TimeSpan date_difference;

		date_difference = todays_date.Subtract(date_of_birth);

			

		//AGE_ALGORITHM

		int total_days = date_difference.Days;

		int calculated_ageYY, calculated_ageMM, calculated_ageDD, remaining_days;

		if ((total_days % 365) == 0)

		{

			  calculated_ageYY = total_days / 365;

			  calculated_ageMM = 0;

			  calculated_ageDD = 0;

		}

		else

		{

			 calculated_ageYY = total_days / 365;

			 remaining_days = total_days % 365;

			 if ((remaining_days % 30) == 0)

			 {

				  calculated_ageMM = remaining_days / 30;

				  calculated_ageDD = 0;

			 }

			 else

			  {

				  calculated_ageMM = remaining_days / 30;

				  calculated_ageDD = remaining_days % 30;

			  }

		 }

		 //Displaying the  result to the text-box

		 txtTaxCalcForOthers_AgeYY.Text = calculated_ageYY.ToString();

		 txtTaxCalcForOthers_AgeMM.Text = calculated_ageMM.ToString();

		 txtTaxCalcForOthers_AgeDD.Text = calculated_ageDD.ToString();

}

catch

{

}
 
At first glance, code looks okay (except for the fact that the final output will never be accurate since there is no consideration for months with 31 days, leap year etc.)!

What is the "bug" you are talking about when the timespan is less than 365?
 
At first glance, code looks okay (except for the fact that the final output will never be accurate since there is no consideration for months with 31 days, leap year etc.)!

What is the "bug" you are talking about when the timespan is less than 365?

ya mate, the code is ok, and i am using it in the program right now.

Say if the age is less then 365, i.e. the date-difference in days is less then 365 (say for example : 364)

Now year =0, month = 12, days = 4, but it should be like year=0, month=11,days=29
<


how to consider the 31days and leap year.

@others, any idea, how the age is calculated in case of income-tax calculation, for senior and very-senior citizen classification ??
 
^ Calendar date is considered. If a person is born on say 19th of February, his age is increased by 1 year for every 19th February he has lived. There is usually no concept of months in official documentation.

If you are looking to address this, you need to take into account the date rather than use simple divisions and modulos like you have done here.
 
#[member='agantuk'], can't you help me with this?

If you are looking to address this, you need to take into account the date rather than use simple divisions and modulos like you have done here.
 
Refer the example I gave. You need to count the number of months based on the date and not on number of days. If date of birth is given as 21st January 2012, after the year calculation, you will need to do something like subtract the birth month (1) from the previous month (3) if the date (21) has not yet passed this month. If it has, then subtract the birth month from the current month. Handle scenarios where the current month number is less than birth month number etc. You get the idea.
 
try this for age :

if (todays_date.Months > date_of_birth.Months )

{txtTaxCalcForOthers_AgeYY.Text = todays_date.Years.Subtract(date_of_birth.Years).ToString();

txtTaxCalcForOthers_AgeMM.Text = todays_date.Months.Subtract(date_of_birth.Months).ToString();

}

else

{txtTaxCalcForOthers_AgeYY.Text = (todays_date.Years.Subtract(date_of_birth.Years) -1 ).ToString();

txtTaxCalcForOthers_AgeMM.Text = (todays_date.Months.Subtract(date_of_birth.Months)+ 12).ToString();

}

txtTaxCalcForOthers_AgeDD.Text = todays_date.Years.Days(date_of_birth.Days).ToString();

Havent checked this code on a compiler, so please check for syntax errors if any. This is just to give you an idea. If it doesnt make any sense. let me know, will try to explain the logic behind it. And i didnt factor in the scenario where the current date (day) is lesser than the b'day date. It will follow the same logic, you can do it easily if you get the logic.
 
can you try this ?

Code:
  private void CalculateAge1()

		{

			DateTime todays_date, date_of_birth;

			todays_date = DateTime.Today;

			//Date of Birth is accepted via user input at the date_time_picker

			date_of_birth = dtpTaxCalcForOthers_DOB.Value;

			int yrDiff = todays_date.Year - date_of_birth.Year;

			int moDiff = todays_date.Month - date_of_birth.Month;

			int daDiff = todays_date.Day - date_of_birth.Day;

			int yrs = 0;

			int mnths = 0;

			int dys = 0;

			if (daDiff >= 0)

			{

				yrs = (yrDiff * 12 + moDiff) / 12;

				mnths = (yrDiff * 12 + moDiff) % 12;

				dys = daDiff;

			}

			else if (daDiff < 0)

			{

				yrs = (yrDiff * 12 + moDiff - 1) / 12;

				mnths = (yrDiff * 12 + moDiff - 1) % 12;

				dys = DateTime.DaysInMonth(date_of_birth.Year, date_of_birth.Month) + daDiff;

			}

			txtTaxCalcForOthers_AgeYY.Text = yrs.ToString();

			txtTaxCalcForOthers_AgeMM.Text = mnths.ToString();

			txtTaxCalcForOthers_AgeDD.Text = dys.ToString();

		}
 
#[member='systembuilder'], i have tried a similar kind of algo in C, but it is not much accurate

Check spoiler, very old codes, so variable name are messy
<


Code:
main()

{

/*Programmer - CA50 Date : 12.08.2007*/

int a1,a2,a3,a4,a5,a6,a7,d,m,y,pd,pm,py,p,q,r,s,t=0,u,v=0,w;

printf("\n\n*************************** Welcome to Age Calculator **************************");

printf("\n\nEnter the date on which you were born [ 1-31]  ");

scanf("%d", &d);

printf("Enter the month on which you were born [ 1-12 ]  ");

scanf("%d", &m);

printf("Enter the year on which you were born  ");

scanf("%d", &y);

printf("\nEnter today`s date [ 1-31 ] ");

scanf("%d", &pd);

printf("Enter current month [ 1-12 ] ");

scanf("%d", &pm);

printf("Enter current year ");

scanf("%d", &py);

if((d>31)||(m>12)||(pd>31)||(pm>12))

  printf("\n\nCan`t you read properly. Check your calender and return back ...");

else

{

  p=py-y;

  if(m<=pm)

	  q=pm-m;

  else

   {

		   q=12+pm-m;

    v=1;

   }

  if(d<=pd)

	  r=pd-d;

  else

   {

	    r=30+pd-d;

    t=1;

   }

  u=q-t;

  w=p-v;

  a5=a1+a4;

		 printf("\nYour entered date of birth is %d-%d-%d",d,m,y);

  printf("\nToday`s date is %d-%d-%d",pd,pm,py);

  printf("\nYour age is %d-years %d-months %d-days.\n\n",w,u,r);

  if((d==pd)&&(m==pm))

	 printf("	  -HAPPY B`DAY TO YOU-	 from CA50.");

}

printf("\nPress any key to exit...\n");

getch();

}
 
#[member='systembuilder'], i have tried a similar kind of algo in C, but it is not much accurate

Check spoiler, very old codes, so variable name are messy
<


Code:
main()

{

/*Programmer - CA50 Date : 12.08.2007*/

int a1,a2,a3,a4,a5,a6,a7,d,m,y,pd,pm,py,p,q,r,s,t=0,u,v=0,w;

printf("\n\n*************************** Welcome to Age Calculator **************************");

printf("\n\nEnter the date on which you were born [ 1-31]  ");

scanf("%d", &d);

printf("Enter the month on which you were born [ 1-12 ]  ");

scanf("%d", &m);

printf("Enter the year on which you were born  ");

scanf("%d", &y);

printf("\nEnter today`s date [ 1-31 ] ");

scanf("%d", &pd);

printf("Enter current month [ 1-12 ] ");

scanf("%d", &pm);

printf("Enter current year ");

scanf("%d", &py);

if((d>31)||(m>12)||(pd>31)||(pm>12))

  printf("\n\nCan`t you read properly. Check your calender and return back ...");

else

{

  p=py-y;

  if(m<=pm)

	  q=pm-m;

  else

   {

		   q=12+pm-m;

	v=1;

   }

  if(d<=pd)

	  r=pd-d;

  else

   {

		r=30+pd-d;

	t=1;

   }

  u=q-t;

  w=p-v;

  a5=a1+a4;

		 printf("\nYour entered date of birth is %d-%d-%d",d,m,y);

  printf("\nToday`s date is %d-%d-%d",pd,pm,py);

  printf("\nYour age is %d-years %d-months %d-days.\n\n",w,u,r);

  if((d==pd)&&(m==pm))

	 printf("	  -HAPPY B`DAY TO YOU-	 from CA50.");

}

printf("\nPress any key to exit...\n");

getch();

}

not accurate as in ?
 
#[member='systembuilder'], here are the codes

[attachment=12681:Age_calculator.zip]

EDIT: codes updated with #luster algo
 

Attachments

  • Age_calculator.zip
    61 KB · Views: 279
I dont know .Net but isn't there a isnull , nullif function in .net so to use default values when year is not specified ?
 
#[member='dinjo'], sorry mate, i am also new and learning.

Some expert / experience once can provide answer to your query
 
Here's a sample code I wrote in C++.

Hope this helps.

Code:
int MonthsToDays(int tMonth, int tYear)

{

if(tMonth == 1 || tMonth == 3 || tMonth == 5 || tMonth == 7

  || tMonth == 8 || tMonth == 10 || tMonth == 12)

  return 31;

else if(tMonth == 2)

{

  if(tYear % 4 == 0)

	return 29;

  else

   return 28;

}

else

  return 30;

}

int _tmain(int argc, _TCHAR* argv[])

{

//inputs: birth year

int mYear = 1983, mMonth=9, mDay=16;

//today

int tYear= 2012, tMonth=3, tDay = 1;

int mYearDiff = tYear - mYear;

int mMonDiff = tMonth - mMonth;

if(mMonDiff < 0)

{

  mYearDiff = mYearDiff -1;

  mMonDiff = mMonDiff + 12;

}

int mDayDiff = tDay - mDay;

if(mDayDiff < 0)

{

  if(mMonDiff > 0)

  {

   mMonDiff = mMonDiff - 1;

   mDayDiff = mDayDiff + MonthsToDays(tMonth-1, tYear);

  }

  else

  {

   mYearDiff = mYearDiff -1;

   mMonDiff = 11;

   mDayDiff = mDayDiff + MonthsToDays(tMonth-1, tYear);;

  }

}

cout<<"\n Years : "<<mYearDiff<<" Month : "<<mMonDiff<<" Days : "<<mDayDiff<<endl;

return 0;

}
 
#[member='mathrisk'], thanks for your code, can you explain this line : int _tmain(int argc, _TCHAR* argv[])

thats the normal main() function - equivalent to "int main(int argc, char ** argv) "

In Visual studio creating new project its automatically generates like that. Never cared to change that.
<
 
^ say the birthday is march 28th 2011, shouldn't the age today should be 1 year ? it displays 11 months 30 days

if the birthday is march 27th 2011, the age is displayed as 12 months 1 days which i guess is wrong
 
#[member='systembuilder'], i have checked it mate, but there seems to be some error.

if entered DOB : 27-03-2011 age = 0-years, 12-months, 1-days

- but 12 months should be 1 years

if entered DOB : 28-03-2011 age = 0-years, 11-months, 30-days

- now where is the complete 12-month, 0-days ??
 
Back
Top