Finding Age from DOB

  • Thread starter Thread starter conckrish
  • Start date Start date
C

conckrish

Hi all,

Can anyone tell me how to find out the exact AGE from Date of
Birth ( DateTime) in C#?? I have tried with
DateTime.Now.Subtract(dob).But I coudlnt get the exact age.. Is there
any property available for this??? Plz help me....


Thanx,
James..
 
Can anyone tell me how to find out the exact AGE from Date of
Birth ( DateTime) in C#??

Depends what you mean by *exact* age... How accurate are you trying to be
here?
 
James,

Why cant u jus add a reference to VisualBasic and use Datediff method
to achieve the result?
Or in other case, we may need to write a custom(?) code to get the
age!!!
If u need further clarification, write me back @
(e-mail address removed).

Thanks,
Venkat
 
Hi all,

Can anyone tell me how to find out the exact AGE from Date of
Birth ( DateTime) in C#?? I have tried with
DateTime.Now.Subtract(dob).But I coudlnt get the exact age.. Is there
any property available for this??? Plz help me....


Thanx,
James..
If I were born on 31st May 1946 then tomorrow I would be 60. Today I am
only 59 ;-)

DateTime dob = new DateTime(1946, 5, 31);
DateTime nn = new DateTime(2006, 5, 30);
TimeSpan age = nn - dob;
double ageInYears = age.Days / 365.25;

so I could either Math.Round(ageInYears) to get 60
or
Math.Truncate(ageInYears) to get 59.

Of course this example is a bit simple in that we are very close to 60.
Let the group know if this doesn't solve your particular problem - I'm
sure there are many ways to address this question.

Eddie
 
Why cant u jus add a reference to VisualBasic and use Datediff method
to achieve the result?

There's no need whatsoever to do that - the TimeSpan object will do just as
well...
 
Nothing in-built that I know of. Leap years are always the trick
(technically not always 1-in-4) ... not hugely graceful, but the following
is at least easy to understand... (done this way as DayOfYear is not so
reliable in a leap year):

Marc

public static void Main() {
DateTime dob = new DateTime(1946, 5, 31);
DateTime today = DateTime.Today, tomorrow = today.AddDays(1);

Console.WriteLine(GetAge(dob, today));
Console.WriteLine(GetAge(dob, tomorrow));

}
public static int GetAge(DateTime dob, DateTime from) {
int years = from.Year - dob.Year;
if ((dob.Month > from.Month) || (dob.Month == from.Month && dob.Day
from.Day))
years--; // haven't had a birthday yet
return years;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top