I write a code in c# for find the birth age. But how can i enter the date in the one only on one text box and calculate the age between the birth date and the current date.help me please !!
Asked
Active
Viewed 392 times
2 Answers
0
First of all you must create a DateTime from the text box text. This can be done with DateTime.Parse()
or better DateTime.TryParse()
.
string text = "06/25/2016";
DateTime date = DateTime.Parse(text);
TimeSpan duration = DateTime.Now - date;
int years = (int)(duration.TotalDays / 365.25);
For an exact result also look at Noda Time like here: Format A TimeSpan with years

Community
- 1
- 1

Christian Held
- 2,321
- 1
- 15
- 26
0
var birthDateInput = yourTextBox.Text;
DateTime birthDate;
TimeSpan age;
if(DateTime.TryParse(out birthDate))
{
age = DateTime.Now - birthDate;
}
When this is done, if the input string is a valid date then age
will contain a TimeSpan
representing the elapsed time. You'd probably want a little more validation. If the user enters a date in the future then the age will be negative.

Scott Hannen
- 27,588
- 3
- 45
- 62