Aug 29, 2010

# Convert TimeSpan to year, month, date (Age Calculation) in .NET

Generally, it is required to express Datetime difference in terms of year, month or day format. Basic example of this is the Age calculation. In .NET Date difference is expressed in timespan. If you require age only in Year then

```
//txt1 = TextBox for Birthdate Input.
DateTime dt1 = Convert.ToDateTime(txt1.Text);
DateTime dt2 = DateTime.Now;
if (dt1.DayOfYear <= dt2.DayOfYear)
{
lbl.Text = (dt2.Year-dt1.Year).ToString();
}
else
{
lbl.Text = (dt2.Year-dt1.Year - 1).ToString();
}
```

But if you require month and date as well

```protected void btn_Click(object sender, EventArgs e)
{
int years=-1,months=-1,days=-1;
DateTime birthDate = Convert.ToDateTime(txt1.Text);
TimeSpanToDate (DateTime.Now, birthDate,out years,out months,out days);
Response.Write("Years: "+ years.ToString()+ " Months: "+ months.ToString()+" Days: "+ days.ToString());
}
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;
}
```

Enjoy it.

• TooTough

what if:months= 12 * (d1.Year – d2.Year) + (d1.Month – d2.Month);
d1.month < d2.month ?

months will be a negative number.