Possible Duplicate:
How do I calculate someone’s age in C#?
I want to write an ASP.NET helper method which returns the age of a person given his or her birthday.
I've tried code like this:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
return (DateTime.Now - birthday); //??
}
But it's not working. What is the correct way to calculate the person's age based on their birthday?
This question is related to
c#
asp.net-mvc
date-arithmetic
I do it like this:
(Shortened the code a bit)
public struct Age
{
public readonly int Years;
public readonly int Months;
public readonly int Days;
}
public Age( int y, int m, int d ) : this()
{
Years = y;
Months = m;
Days = d;
}
public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
if( startDate.Date > endDate.Date )
{
throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
}
int years = endDate.Year - startDate.Year;
int months = 0;
int days = 0;
// Check if the last year, was a full year.
if( endDate < startDate.AddYears (years) && years != 0 )
{
years--;
}
// Calculate the number of months.
startDate = startDate.AddYears (years);
if( startDate.Year == endDate.Year )
{
months = endDate.Month - startDate.Month;
}
else
{
months = ( 12 - startDate.Month ) + endDate.Month;
}
// Check if last month was a complete month.
if( endDate < startDate.AddMonths (months) && months != 0 )
{
months--;
}
// Calculate the number of days.
startDate = startDate.AddMonths (months);
days = ( endDate - startDate ).Days;
return new Age (years, months, days);
}
// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...
}
Another clever way from that ancient thread:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
I don't really understand why you would make this an HTML Helper. I would make it part of the ViewData dictionary in an action method of the controller. Something like this:
ViewData["Age"] = DateTime.Now.Year - birthday.Year;
Given that birthday is passed into an action method and is a DateTime object.
Source: Stackoverflow.com