Rifshan
Rifshan

Reputation: 153

How to calculate age from date

I see that this has been asked many times. A lot of people have answered, but i haven't been able to make it work.

This is the code I got from my searches:

public static int CalculateAge(DateTime birthDate)
{
    DateTime now = DateTime.Today;
    int years = now.Year - birthDate.Year;

    if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        --years;

    return years;
}

How do I supply the birth date from a TextBox?

Im using Jquery calender to supply date into a TextBox3 in dd-mm-yy format..

Now I want to calculate age from the supplied date and then on a button click to save in the DB..

I get the save on DB part, but how do I insert TextBox value into the code above and then use years to save it on my button click event?

Upvotes: 0

Views: 1055

Answers (1)

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

So here, how do i supply the birth date from a TextBox?

With supply, if you mean to get it's Text as DateTime, you can parse it to DateTime like;

DateTime dt;
if(DateTime.TryParseExact(TextBox3.Text, "dd-MM-yy",
                          CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
   // now you can use dt with subtract process as a DateTime
}

or if dd-MM-yy format is a standard date and time format for your CurrentCulture, you can directly use DateTime.Parse() method like;

var dt = DateTime.Parse(TextBox3.Text);

By the way, mm specifier is for minutes, MM is for months. Don't forget to add System.Globalization namespace to use them.

Read also: Calculate age in C#

Upvotes: 5

Related Questions