[c#] How to calculate an age based on a birthday?

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

The answer is


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to date-arithmetic

How to subtract hours from a date in Oracle so it affects the day also MySQL Select last 7 days Calculating days between two dates with Java How to find the duration of difference between two dates in java? Check if year is leap year in javascript Add a month to a Date Get the difference between two dates both In Months and days in sql Oracle Date - How to add years to date How can I do time/hours arithmetic in Google Spreadsheet? Oracle DateTime in Where Clause?