0

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Rifshan
  • 153
  • 1
  • 4
  • 13
  • Think of this logically. how do you calculate the year difference? Take the current year and subtract that from the supplied year in the DOB. Simple. – Ahmed ilyas Jan 02 '15 at 15:47
  • 1
    possible duplicate of [How do I calculate someone's age in C#?](http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c) – Uriil Jan 02 '15 at 15:49
  • 1
    Logic isnt the problem, i dunno how to pass the BirthDate from a TextBox into the code above.. – Rifshan Jan 02 '15 at 15:50

1 Answers1

5

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#

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364