1

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?

1

4 Answers 4

1

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 U.S. 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.

0

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.

0

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
0
int ag1;
string st, ag;
void agecal()
{
    st = TextBox4.Text;
    DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
    dtfi.ShortDatePattern = "MM/dd/yyyy";
    dtfi.DateSeparator = "/";
    DateTime dt = Convert.ToDateTime(st, dtfi);
    ag1 = int.Parse(dt.Year.ToString());
    int years = DateTime.Now.Year - ag1;
    ag = years.ToString();
    TextBox3.Text = ag.ToString();
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.