Calculate age in year,month & days


Hi,

Here we are calculating age in years,months and days using a birth date of the person.

here is function to calculate a age,

public void TimeSpanToDate(DateTime d1, DateTime d2, out int years, out int months, out int days)
{
// compute & return the difference of two dates,
// returning years, months & days
// d1 should be the larger (newest) of the two dates
// we want d1 to be the larger (newest) date
// flip if we need to
if (d1 < d2)
{
DateTime d3 = d2;
d2 = d1;
d1 = d3;
}

// compute difference in total months
months = 12 * (d1.Year – d2.Year) + (d1.Month – d2.Month);

// based upon the ‘days’,
// adjust months & compute actual days difference
if (d1.Day < d2.Day)
{
months–;
days = DateTime.DaysInMonth(d2.Year, d2.Month) – d2.Day + d1.Day;
}
else
{
days = d1.Day – d2.Day;
}
// compute years & actual months
years = months / 12;
months -= years * 12;
}

the function use like this,

protected void btnCalculate_Click(object sender, EventArgs e)
{
int years = -1, months = -1, days = -1;
DateTime birthDate = Convert.ToDateTime(txtbirthdate.Text);
TimeSpanToDate(DateTime.Now, birthDate, out years, out months, out days);
lblAge.Text = “Years: ” + years.ToString() + ” ; Months: ” + months.ToString() + ” ; Days: ” + days.ToString();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: