Hey guys,
Im using asp.net in visual studio and im kinda new to the whole thing.
Im actually making a multi view form, and in the second view i need to calculate a persons age based on the date of birth that has been typed in view 1.Anyone know how to?I thnk its through regular expressions but we havent really been taught how to do that:S

Recommended Answers

All 6 Replies

Lets say that your DOB is being display by a textbox id = "txtDOB" then you can do this.

int years = DateTime.Today.Year - Convert.ToDateTime(txtDOB.Text).Year;

Hmmm..So how do i get years to be displayed in view two?

What control do you want to render the age in?

The only drawback I can see with jbisono's suggestion is that it may not be 100% accurate. As an example, my B-Day is in December 1978... if we use the formula:

int years = DateTime.Today.Year - Convert.ToDateTime(txtDOB.Text).Year;

Then what we get is 2010 - 1978 = 32. However, at least for the next few months, I'm still 31. It is possible, however, to extend jbisono's example to include the full range of date (year, month, day) and perform a more accurate subtraction that would take the partial year into account and provide a correct age. Just requires a bit more calculation and creativity :twisted:

You are totally right Lusiphur. Thanks for correcting me. Roses89 if you need help to complete the code let us know.

If you are using calender control then use the TimeSpan property.

Get one Calender Control,textbox and Button.

dt = Calendar1.SelectedDate
        ts = Date.Now - dt
        TextBox1.Text = ts.Days.ToString

dt is object of datetime, ts is for timespan

This code in Visual Studio Visual basic.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.