简体   繁体   中英

Given string input, how do I calculate age in C#?

I want to calculate a person's present age. The date of birth (DOB) data is entered using a TextBox and my database stores DOB as a varchar.

How do I find the current age from this birth date?

There are lots of things you need to do here. First of all you need a way to parse the date stored in the database, originally typed in manually by a user. That is a difficult task, because users tend to type just about anything.

Start off with DateTime.Parse() , deal with all the errors you will get, and yes, you will get errors. How do you know, for instance, what "09/10/11" means? Is this an American date or a British one?

One possibility is to switch from TextBox to some form of MaskedTextBox to force the user to always enter the date in the same format, and store the date properly as a true date in the database.

After you have a proper DateTime value, you could use simple subtraction to get the person's age, but the TimeSpan value you get back isn't completely useful, as I assume that you need to output the person's age in full years.

// Assuming dateOfBirth is a DateTime value
TimeSpan age = DateTime.Today - dateOfBirth;

The age variable here holds the amount of time that has passed from the date of birth until today. Given the fact that years differ in length, this is not the best option. I would do something like this:

DateTime today = DateTime.Today;
int years = today.Year - dateOfBirth.Year;
if (dateOfBirth.Month > today.Month) {
    --years;
}
else if (dateOfBirth.Month == today.Month && dateOfBirth.Day > today.Day) {
    --years;
}
// TODO: Output the years variable.

If the date is always in the same format, you can use DateTime.TryParseExact() - however this doesn't seem to be the case here.

Perhaps this library helps for you, the author had the same problem: http://www.codeproject.com/Articles/33298/C-Date-Time-Parser

This is no way to guarantee though that every format can be parsed.

您可以将DOB string into DateTime object ,然后可以计算年龄:)

DateTime dateDOB = DateTime.Parse(txt_dob.Text);

int now = int.Parse(DateTime.Today.ToString("yyyyMMdd"));

int dob = int.Parse(dateDOB.ToString("yyyyMMdd"));

string dif = (now - dob).ToString();

string age = "0";

if (dif.Length > 4)

age = dif.Substring(0, dif.Length - 4);

txt_age.Text = age.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM