Sunday, February 12, 2012

Calculating Ages

When users register with my site they give me their DoB, how can I work out an age from it. I was thinkin about doing it from the year, but that isnt very accurate. Can anyone help? thanks si!

ps Id only want to work out how many years old they are. si!

You started on the right track. Subtract the DOB from Now.Date (or GETDATE()), and if the (DOB.Month >= Now.Month And DOB.Day > Now.Day) then this year's birthday is in the future, so subtract 1.

|||

Minus one date from the other and the result will be a TimeSpan. e.g.

Dim dAs New Date
Dim tAs New TimeSpan
d = System.DateTime.Today
t = d.Subtract("01/01/1950")
You can then display their age by using the relevant properties from the TimeSpan object.|||

Sorry can you tell me what that is in C# please. Si!

|||

There's no difference apart from how you declare the variables. e.g

DateTime d =new DateTime();TimeSpan t =new TimeSpan();d = System.DateTime.Today;t = d.Subtract("01/01/1950");
|||

This would work better, and you wouldn't have to calculate the years from days, which the timespan requires:

DateTime _today = DateTime.Now.Date;// strip the time.DateTime _DOB = DateTime.Parse(@."10/24/1980").Date;// strip the time.int _Age = 0;// get the difference in years._Age = _today.Year - _DOB.Year;//our user was born in October. If the current date is before October 24,// then the user hasn't had his birthday for this year. // 2007 - 1980 = 27, 27-1 = 26 years old.if ( _today.Month <= _DOB.Month && _today.Day <_DOB.Day ){//subtract 1 _Age -= 1;}//_Age now contains the correct age.
|||

Even though I used October above, the if statement applies to every possiblity. This is as accurate as you can get in calculating age, as it takes into account whether the person has reached their birthday yet this year.

No comments:

Post a Comment