Exact age calculation

Possible Duplicate:
How do I calculate someone's age in C#?

Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age?

Maybe

DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;

The result of year is 32.77405678074

Could this code be OK?


If you were born on January 12th 1975, you would be 33 years old today.

If you were born on December 1st 1975, you would be 32 years old today.

If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style.


Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?

My guess would be that this is a localization issue, though I don't know how it would happen, since (at least for me) the profile has you fill out your age in the format "YYYY/MM/DD". But your birthday is one that reads as a valid date (January 12th) in traditional US settings, so this is the area I'd look into. I was born in 1975, also, and my birthday is next month, and it's got my age right.


Actually, because of leap years, your code would be off. Since the timespan object has no TotalYears property the best way to get it would be this

Pardon the VB.Net

Dim myAge AS Integer = DateTime.Now.year - BirthDate.year
If Birthdate.month < DateTime.Now.Month _
OrElse BirthDate.Month = DateTime.Now.Month AndAlso Birthdate.Day < DateTime.Now.Day Then
MyAge -= 1
END IF
链接地址: http://www.djcxy.com/p/54364.html

上一篇: 年龄计算

下一篇: 精确的年龄计算