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

  • Thread starter Thread starter needin4mation
  • Start date Start date
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!
 
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?
 
How about:

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

DateTime now = DateTime.Now;

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