Come calcolare un'età in base a un compleanno? [duplicare
-
25-09-2019 - |
Domanda
Possibile duplicato:
Come calcolo l'età di qualcuno in C#?
Voglio scrivere un metodo ASP.NET Helper che restituisce l'età di una persona data il suo compleanno.
Ho provato il codice come questo:
public static string Age(this HtmlHelper helper, DateTime birthday)
{
return (DateTime.Now - birthday); //??
}
Ma non funziona. Qual è il modo corretto per calcolare l'età della persona in base al loro compleanno?
Soluzione
StackOverFlow utilizza tale funzione per determinare l'età di un utente.
La risposta data è
DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;
Quindi il tuo metodo Helper sarebbe
public static string Age(this HtmlHelper helper, DateTime birthday)
{
DateTime now = DateTime.Today;
int age = now.Year - birthday.Year;
if (now < birthday.AddYears(age)) age--;
return age.ToString();
}
Oggi uso una versione diversa di questa funzione per includere una data di riferimento. Questo mi permette di avere l'età di qualcuno in una data futura o in passato. Questo viene utilizzato per il nostro sistema di prenotazione, in cui è necessaria l'età in futuro.
public static int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age;
}
Altri suggerimenti
Un altro modo intelligente da quello Antico filo:
int age = (
Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) -
Int32.Parse(birthday.ToString("yyyyMMdd"))) / 10000;
Lo faccio così:
(Abbreviato un po 'il codice)
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...
}
Non capisco davvero perché lo renderesti un aiutante HTML. Lo farei parte del dizionario ViewData in un metodo di azione del controller. Qualcosa come questo:
ViewData["Age"] = DateTime.Now.Year - birthday.Year;
Dato che il compleanno viene trasmesso in un metodo di azione ed è un oggetto DateTime.