954,595 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Calculate age based on DOB?

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

Roses89
Junior Poster in Training
55 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

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;
jbisono
Posting Pro in Training
442 posts since May 2009
Reputation Points: 71
Solved Threads: 59
 

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

Roses89
Junior Poster in Training
55 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
 

What control do you want to render the age in?

jbisono
Posting Pro in Training
442 posts since May 2009
Reputation Points: 71
Solved Threads: 59
 

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:

Lusiphur
Posting Shark
Team Colleague
966 posts since Jun 2010
Reputation Points: 207
Solved Threads: 127
 

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

jbisono
Posting Pro in Training
442 posts since May 2009
Reputation Points: 71
Solved Threads: 59
 

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.

virusisfound
Junior Poster
172 posts since Jun 2010
Reputation Points: 10
Solved Threads: 2
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You