Is this a good way to get an age from a date of birth?

N

needin4mation

Hi, this is what I did:

//this will work even though a decimal is returned because
//everyone will have a double digit age returned
//unless 9 and under or over 99 are in the database;
//can work to catch wrongly entered dates of birth;
//it is a given all ages must be two digits; there will
//never be otherwise in this scenario

DateTime dtThen = new DateTime ();
dtThen = Convert.ToDateTime(PerReader["dob"]);
DateTime dtNow = DateTime.Now;
TimeSpan ts = dtNow - dtThen;
double age = (ts.TotalDays / 365);
txtAge.Text = age.ToString().Substring(0,2);

Comments and improvements are welcome on how to get someone's age from
a date of birth in a database. Thanks!
 
B

Brendan Green

Well, the first thing that I can see as an issue is that not every year has
365 days.

It looks to me that you're trying to get the whole number of years for their
age?
 
B

Brendan Green

How about:

DateTime dob = new DateTime(1970, 01, 01);

DateTime now = DateTime.Now;

Console.WriteLine(now.Year - dob.Year);
 

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

Top