<p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p>

[{'answer_id': 22, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 6, 'selected': False, 'text': '<p>The best way that I know of because of leap years and everything is:</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime birthDate = new DateTime(2000,3,1);\nint age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);\n</code></pre>\n'}, {'answer_id': 229, 'author': 'Michael Stum', 'author_id': 91, 'author_profile': 'https://Stackoverflow.com/users/91', 'pm_score': 7, 'selected': False, 'text': "<p>Another function, not by me but found on the web and refined it a bit:</p>\n\n<pre><code>public static int GetAge(DateTime birthDate)\n{\n    DateTime n = DateTime.Now; // To avoid a race condition around midnight\n    int age = n.Year - birthDate.Year;\n\n    if (n.Month &lt; birthDate.Month || (n.Month == birthDate.Month &amp;&amp; n.Day &lt; birthDate.Day))\n        age--;\n\n    return age;\n}\n</code></pre>\n\n<p>Just two things that come into my mind: What about people from countries that do not use the Gregorian calendar? DateTime.Now is in the server-specific culture I think. I have absolutely zero knowledge about actually working with Asian calendars and I do not know if there is an easy way to convert dates between calendars, but just in case you're wondering about those Chinese guys from the year 4660 :-)</p>\n"}, {'answer_id': 1404, 'author': 'Mike Polen', 'author_id': 212, 'author_profile': 'https://Stackoverflow.com/users/212', 'pm_score': 12, 'selected': True, 'text': '<p>An easy to understand and simple solution.</p>\n<pre class="lang-cs prettyprint-override"><code>// Save today\'s date.\nvar today = DateTime.Today;\n\n// Calculate the age.\nvar age = today.Year - birthdate.Year;\n\n// Go back to the year in which the person was born in case of a leap year\nif (birthdate.Date &gt; today.AddYears(-age)) age--;\n</code></pre>\n<p>However, this assumes you are looking for the <em>western</em> idea of the age and not using <a href="https://en.wikipedia.org/wiki/East_Asian_age_reckoning" rel="noreferrer"><em>East Asian reckoning</em></a>.</p>\n'}, {'answer_id': 3261, 'author': 'David Wengier', 'author_id': 489, 'author_profile': 'https://Stackoverflow.com/users/489', 'pm_score': 6, 'selected': False, 'text': '<p>This is the version we use here. It works, and it\'s fairly simple. It\'s the same idea as Jeff\'s but I think it\'s a little clearer because it separates out the logic for subtracting one, so it\'s a little easier to understand.</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)\n{\n    return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear &lt; dateAsAt.DayOfYear ? 0 : 1);\n}\n</code></pre>\n\n<p>You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear.</p>\n\n<p>Obviously this is done as an extension method on <code>DateTime</code>, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in <code>DateTime.Now</code>, just for completeness.</p>\n'}, {'answer_id': 11942, 'author': 'ScArcher2', 'author_id': 1310, 'author_profile': 'https://Stackoverflow.com/users/1310', 'pm_score': 10, 'selected': False, 'text': '<p>This is a strange way to do it, but if you format the date to <code>yyyymmdd</code> and subtract the date of birth from the current date then drop the last 4 digits you\'ve got the age :)</p>\n\n<p>I don\'t know C#, but I believe this will work in any language.</p>\n\n<pre class="lang-cs prettyprint-override"><code>20080814 - 19800703 = 280111 \n</code></pre>\n\n<p>Drop the last 4 digits = <code>28</code>.</p>\n\n<p>C# Code:</p>\n\n<pre class="lang-cs prettyprint-override"><code>int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));\nint dob = int.Parse(dateOfBirth.ToString("yyyyMMdd"));\nint age = (now - dob) / 10000;\n</code></pre>\n\n<p>Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static Int32 GetAge(this DateTime dateOfBirth)\n{\n    var today = DateTime.Today;\n\n    var a = (today.Year * 100 + today.Month) * 100 + today.Day;\n    var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;\n\n    return (a - b) / 10000;\n}\n</code></pre>\n'}, {'answer_id': 24242, 'author': 'user2601', 'author_id': 2601, 'author_profile': 'https://Stackoverflow.com/users/2601', 'pm_score': 5, 'selected': False, 'text': "<p>I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query:</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.Sql;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class UserDefinedFunctions\n{\n    [SqlFunction(DataAccess = DataAccessKind.Read)]\n    public static SqlInt32 CalculateAge(string strBirthDate)\n    {\n        DateTime dtBirthDate = new DateTime();\n        dtBirthDate = Convert.ToDateTime(strBirthDate);\n        DateTime dtToday = DateTime.Now;\n\n        // get the difference in years\n        int years = dtToday.Year - dtBirthDate.Year;\n\n        // subtract another year if we're before the\n        // birth day in the current year\n        if (dtToday.Month &lt; dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month &amp;&amp; dtToday.Day &lt; dtBirthDate.Day))\n            years=years-1;\n\n        int intCustomerAge = years;\n        return intCustomerAge;\n    }\n};\n</code></pre>\n"}, {'answer_id': 141644, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I think the TimeSpan has all that we need in it, without having to resort to 365.25 (or any other approximation). Expanding on Aug\'s example:</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime myBD = new DateTime(1980, 10, 10);\nTimeSpan difference = DateTime.Now.Subtract(myBD);\n\ntextBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";\n</code></pre>\n'}, {'answer_id': 168703, 'author': 'James Curran', 'author_id': 12725, 'author_profile': 'https://Stackoverflow.com/users/12725', 'pm_score': 7, 'selected': False, 'text': '<p>My suggestion</p>\n\n<pre class="lang-cs prettyprint-override"><code>int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);\n</code></pre>\n\n<p>That seems to have the year changing on the right date. (I spot tested up to age 107.)</p>\n'}, {'answer_id': 877247, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:</p>\n\n<pre><code>public void LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n    int years = 0;\n    int months = 0;\n    int days = 0;\n\n    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n    while (tmpMyDOB.AddYears(years).AddMonths(months) &lt; tmpFutureDate)\n    {\n        months++;\n\n        if (months &gt; 12)\n        {\n            years++;\n            months = months - 12;\n        }\n    }\n\n    if (FutureDate.Day &gt;= myDOB.Day)\n    {\n        days = days + FutureDate.Day - myDOB.Day;\n    }\n    else\n    {\n        months--;\n\n        if (months &lt; 0)\n        {\n            years--;\n            months = months + 12;\n        }\n\n        days +=\n            DateTime.DaysInMonth(\n                FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month\n            ) + FutureDate.Day - myDOB.Day;\n\n    }\n\n    //add an extra day if the dob is a leap day\n    if (DateTime.IsLeapYear(myDOB.Year) &amp;&amp; myDOB.Month == 2 &amp;&amp; myDOB.Day == 29)\n    {\n        //but only if the future date is less than 1st March\n        if (FutureDate &gt;= new DateTime(FutureDate.Year, 3, 1))\n            days++;\n    }\n\n}\n</code></pre>\n"}, {'answer_id': 877516, 'author': 'SillyMonkey', 'author_id': 88600, 'author_profile': 'https://Stackoverflow.com/users/88600', 'pm_score': 6, 'selected': False, 'text': '<p>Here\'s a one-liner:</p>\n\n<pre class="lang-cs prettyprint-override"><code>int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;\n</code></pre>\n'}, {'answer_id': 1011981, 'author': 'Rajeshwaran S P', 'author_id': 21995, 'author_profile': 'https://Stackoverflow.com/users/21995', 'pm_score': 4, 'selected': False, 'text': '<p>Here is a solution.</p>\n\n<pre><code>DateTime dateOfBirth = new DateTime(2000, 4, 18);\nDateTime currentDate = DateTime.Now;\n\nint ageInYears = 0;\nint ageInMonths = 0;\nint ageInDays = 0;\n\nageInDays = currentDate.Day - dateOfBirth.Day;\nageInMonths = currentDate.Month - dateOfBirth.Month;\nageInYears = currentDate.Year - dateOfBirth.Year;\n\nif (ageInDays &lt; 0)\n{\n    ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);\n    ageInMonths = ageInMonths--;\n\n    if (ageInMonths &lt; 0)\n    {\n        ageInMonths += 12;\n        ageInYears--;\n    }\n}\n\nif (ageInMonths &lt; 0)\n{\n    ageInMonths += 12;\n    ageInYears--;\n}\n\nConsole.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);\n</code></pre>\n'}, {'answer_id': 1595311, 'author': 'RMA', 'author_id': 193184, 'author_profile': 'https://Stackoverflow.com/users/193184', 'pm_score': 9, 'selected': False, 'text': '<p>Here is a test snippet:</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime bDay = new DateTime(2000, 2, 29);\nDateTime now = new DateTime(2009, 2, 28);\nMessageBox.Show(string.Format("Test {0} {1} {2}",\n                CalculateAgeWrong1(bDay, now),      // outputs 9\n                CalculateAgeWrong2(bDay, now),      // outputs 9\n                CalculateAgeCorrect(bDay, now),     // outputs 8\n                CalculateAgeCorrect2(bDay, now)));  // outputs 8\n</code></pre>\n\n<p>Here you have the methods:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public int CalculateAgeWrong1(DateTime birthDate, DateTime now)\n{\n    return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;\n}\n\npublic int CalculateAgeWrong2(DateTime birthDate, DateTime now)\n{\n    int age = now.Year - birthDate.Year;\n\n    if (now &lt; birthDate.AddYears(age))\n        age--;\n\n    return age;\n}\n\npublic int CalculateAgeCorrect(DateTime birthDate, DateTime now)\n{\n    int age = now.Year - birthDate.Year;\n\n    if (now.Month &lt; birthDate.Month || (now.Month == birthDate.Month &amp;&amp; now.Day &lt; birthDate.Day))\n        age--;\n\n    return age;\n}\n\npublic int CalculateAgeCorrect2(DateTime birthDate, DateTime now)\n{\n    int age = now.Year - birthDate.Year;\n\n    // For leap years we need this\n    if (birthDate &gt; now.AddYears(-age)) \n        age--;\n    // Don\'t use:\n    // if (birthDate.AddYears(age) &gt; now) \n    //     age--;\n\n    return age;\n}\n</code></pre>\n'}, {'answer_id': 1811311, 'author': 'azamsharp', 'author_id': 3797, 'author_profile': 'https://Stackoverflow.com/users/3797', 'pm_score': 2, 'selected': False, 'text': '<p>This may work:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public override bool IsValid(DateTime value)\n{\n    _dateOfBirth =  value;\n    var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);\n    if (yearsOld &gt; 18)\n        return true;\n    return false;\n}\n</code></pre>\n'}, {'answer_id': 1913553, 'author': 'Frederik Gheysels', 'author_id': 55774, 'author_profile': 'https://Stackoverflow.com/users/55774', 'pm_score': 2, 'selected': False, 'text': "<p>I've created an Age struct, which looks like this:</p>\n\n<pre><code>public struct Age : IEquatable&lt;Age&gt;, IComparable&lt;Age&gt;\n{\n    private readonly int _years;\n    private readonly int _months;\n    private readonly int _days;\n\n    public int Years  { get { return _years; } }\n    public int Months { get { return _months; } }\n    public int Days { get { return _days; } }\n\n    public Age( int years, int months, int days ) : this()\n    {\n        _years = years;\n        _months = months;\n        _days = days;\n    }\n\n    public static Age CalculateAge( DateTime dateOfBirth, DateTime date )\n    {\n        // Here is some logic that ressembles Mike's solution, although it\n        // also takes into account months &amp; days.\n        // Ommitted for brevity.\n        return new Age (years, months, days);\n    }\n\n    // Ommited Equality, Comparable, GetHashCode, functionality for brevity.\n}\n</code></pre>\n"}, {'answer_id': 1928680, 'author': 'Jon', 'author_id': 234611, 'author_profile': 'https://Stackoverflow.com/users/234611', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a little code sample for C# I knocked up, be careful around the edge cases specifically leap years, not all the above solutions take them into account. Pushing the answer out as a DateTime can cause problems as you could end up trying to put too many days into a specific month e.g. 30 days in Feb.</p>\n\n<pre><code>public string LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n    int years = 0;\n    int months = 0;\n    int days = 0;\n\n    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n    while (tmpMyDOB.AddYears(years).AddMonths(months) &lt; tmpFutureDate)\n    {\n        months++;\n        if (months &gt; 12)\n        {\n            years++;\n            months = months - 12;\n        }\n    }\n\n    if (FutureDate.Day &gt;= myDOB.Day)\n    {\n        days = days + FutureDate.Day - myDOB.Day;\n    }\n    else\n    {\n        months--;\n        if (months &lt; 0)\n        {\n            years--;\n            months = months + 12;\n        }\n        days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;\n\n    }\n\n    //add an extra day if the dob is a leap day\n    if (DateTime.IsLeapYear(myDOB.Year) &amp;&amp; myDOB.Month == 2 &amp;&amp; myDOB.Day == 29)\n    {\n        //but only if the future date is less than 1st March\n        if(FutureDate &gt;= new DateTime(FutureDate.Year, 3,1))\n            days++;\n    }\n\n    return "Years: " + years + " Months: " + months + " Days: " + days;\n}\n</code></pre>\n'}, {'answer_id': 2280982, 'author': 'Elmer', 'author_id': 173109, 'author_profile': 'https://Stackoverflow.com/users/173109', 'pm_score': 5, 'selected': False, 'text': '<p>I use this:</p>\n\n<pre><code>public static class DateTimeExtensions\n{\n    public static int Age(this DateTime birthDate)\n    {\n        return Age(birthDate, DateTime.Now);\n    }\n\n    public static int Age(this DateTime birthDate, DateTime offsetDate)\n    {\n        int result=0;\n        result = offsetDate.Year - birthDate.Year;\n\n        if (offsetDate.DayOfYear &lt; birthDate.DayOfYear)\n        {\n              result--;\n        }\n\n        return result;\n    }\n}\n</code></pre>\n'}, {'answer_id': 3513146, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': '<p>Keeping it simple (and possibly stupid:)).</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);\nTimeSpan ts = DateTime.Now - birth;\nConsole.WriteLine("You are approximately " + ts.TotalSeconds.ToString() + " seconds old.");\n</code></pre>\n'}, {'answer_id': 3652116, 'author': 'AEMLoviji', 'author_id': 440670, 'author_profile': 'https://Stackoverflow.com/users/440670', 'pm_score': 4, 'selected': False, 'text': '<pre><code>private int GetAge(int _year, int _month, int _day\n{\n    DateTime yourBirthDate= new DateTime(_year, _month, _day);\n\n    DateTime todaysDateTime = DateTime.Today;\n    int noOfYears = todaysDateTime.Year - yourBirthDate.Year;\n\n    if (DateTime.Now.Month &lt; yourBirthDate.Month ||\n        (DateTime.Now.Month == yourBirthDate.Month &amp;&amp; DateTime.Now.Day &lt; yourBirthDate.Day))\n    {\n        noOfYears--;\n    }\n\n    return  noOfYears;\n}\n</code></pre>\n'}, {'answer_id': 3869003, 'author': 'Nicholas Carey', 'author_id': 467473, 'author_profile': 'https://Stackoverflow.com/users/467473', 'pm_score': 4, 'selected': False, 'text': '<p>The simplest way I\'ve ever found is this. It works correctly for the US and western europe locales. Can\'t speak to other locales, especially places like China. 4 extra compares, at most, following the initial computation of age.</p>\n\n<pre><code>public int AgeInYears(DateTime birthDate, DateTime referenceDate)\n{\n  Debug.Assert(referenceDate &gt;= birthDate, \n               "birth date must be on or prior to the reference date");\n\n  DateTime birth = birthDate.Date;\n  DateTime reference = referenceDate.Date;\n  int years = (reference.Year - birth.Year);\n\n  //\n  // an offset of -1 is applied if the birth date has \n  // not yet occurred in the current year.\n  //\n  if (reference.Month &gt; birth.Month);\n  else if (reference.Month &lt; birth.Month) \n    --years;\n  else // in birth month\n  {\n    if (reference.Day &lt; birth.Day)\n      --years;\n  }\n\n  return years ;\n}\n</code></pre>\n\n<p>I was looking over the answers to this and noticed that nobody has made reference to regulatory/legal implications of leap day births. For instance, <a href="https://en.wikipedia.org/wiki/February_29#Births" rel="noreferrer">per Wikipedia</a>, if you\'re born on February 29th in various jurisdictions, you\'re non-leap year birthday varies:</p>\n\n<ul>\n<li>In the United Kingdom and Hong Kong: it\'s the ordinal day of the year, so the next day, March 1st is your birthday.</li>\n<li>In New Zealand: it\'s the previous day, February 28th for the purposes of driver licencing, and March 1st for other purposes.</li>\n<li>Taiwan: it\'s February 28th.</li>\n</ul>\n\n<p>And as near as I can tell, in the US, the statutes are silent on the matter, leaving it up to the common law and to how various regulatory bodies define things in their regulations.</p>\n\n<p>To that end, an improvement:</p>\n\n<pre><code>public enum LeapDayRule\n{\n  OrdinalDay     = 1 ,\n  LastDayOfMonth = 2 ,\n}\n\nstatic int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)\n{\n  bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);\n  DateTime cutoff;\n\n  if (isLeapYearBirthday &amp;&amp; !DateTime.IsLeapYear(reference.Year))\n  {\n    switch (ruleInEffect)\n    {\n      case LeapDayRule.OrdinalDay:\n        cutoff = new DateTime(reference.Year, 1, 1)\n                             .AddDays(birth.DayOfYear - 1);\n        break;\n\n      case LeapDayRule.LastDayOfMonth:\n        cutoff = new DateTime(reference.Year, birth.Month, 1)\n                             .AddMonths(1)\n                             .AddDays(-1);\n        break;\n\n      default:\n        throw new InvalidOperationException();\n    }\n  }\n  else\n  {\n    cutoff = new DateTime(reference.Year, birth.Month, birth.Day);\n  }\n\n  int age = (reference.Year - birth.Year) + (reference &gt;= cutoff ? 0 : -1);\n  return age &lt; 0 ? 0 : age;\n}\n</code></pre>\n\n<p>It should be noted that this code assumes:</p>\n\n<ul>\n<li>A western (European) reckoning of age, and</li>\n<li>A calendar, like the Gregorian calendar that inserts a single leap day at the end of a month.</li>\n</ul>\n'}, {'answer_id': 5054317, 'author': 'camelCasus', 'author_id': 624612, 'author_profile': 'https://Stackoverflow.com/users/624612', 'pm_score': 7, 'selected': False, 'text': '<p>The simple answer to this is to apply <code>AddYears</code> as shown below because this is the only native method to add years to the 29th of Feb. of leap years and obtain the correct result of the 28th of Feb. for common years. </p>\n\n<p>Some feel that 1th of Mar. is the birthday of leaplings but neither .Net nor any official rule supports this, nor does common logic explain why some born in February should have 75% of their birthdays in another month.</p>\n\n<p>Further, an Age method lends itself to be added as an extension to <code>DateTime</code>. By this you can obtain the age in the simplest possible way:</p>\n\n<ol>\n<li>List item</li>\n</ol>\n\n<p><strong>int age = birthDate.Age();</strong></p>\n\n<pre><code>public static class DateTimeExtensions\n{\n    /// &lt;summary&gt;\n    /// Calculates the age in years of the current System.DateTime object today.\n    /// &lt;/summary&gt;\n    /// &lt;param name="birthDate"&gt;The date of birth&lt;/param&gt;\n    /// &lt;returns&gt;Age in years today. 0 is returned for a future date of birth.&lt;/returns&gt;\n    public static int Age(this DateTime birthDate)\n    {\n        return Age(birthDate, DateTime.Today);\n    }\n\n    /// &lt;summary&gt;\n    /// Calculates the age in years of the current System.DateTime object on a later date.\n    /// &lt;/summary&gt;\n    /// &lt;param name="birthDate"&gt;The date of birth&lt;/param&gt;\n    /// &lt;param name="laterDate"&gt;The date on which to calculate the age.&lt;/param&gt;\n    /// &lt;returns&gt;Age in years on a later day. 0 is returned as minimum.&lt;/returns&gt;\n    public static int Age(this DateTime birthDate, DateTime laterDate)\n    {\n        int age;\n        age = laterDate.Year - birthDate.Year;\n\n        if (age &gt; 0)\n        {\n            age -= Convert.ToInt32(laterDate.Date &lt; birthDate.Date.AddYears(age));\n        }\n        else\n        {\n            age = 0;\n        }\n\n        return age;\n    }\n}\n</code></pre>\n\n<p>Now, run this test:</p>\n\n<pre><code>class Program\n{\n    static void Main(string[] args)\n    {\n        RunTest();\n    }\n\n    private static void RunTest()\n    {\n        DateTime birthDate = new DateTime(2000, 2, 28);\n        DateTime laterDate = new DateTime(2011, 2, 27);\n        string iso = "yyyy-MM-dd";\n\n        for (int i = 0; i &lt; 3; i++)\n        {\n            for (int j = 0; j &lt; 3; j++)\n            {\n                Console.WriteLine("Birth date: " + birthDate.AddDays(i).ToString(iso) + "  Later date: " + laterDate.AddDays(j).ToString(iso) + "  Age: " + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());\n            }\n        }\n\n        Console.ReadKey();\n    }\n}\n</code></pre>\n\n<p>The critical date example is this:</p>\n\n<p><strong>Birth date: 2000-02-29  Later date: 2011-02-28  Age: 11</strong></p>\n\n<p>Output:</p>\n\n<pre><code>{\n    Birth date: 2000-02-28  Later date: 2011-02-27  Age: 10\n    Birth date: 2000-02-28  Later date: 2011-02-28  Age: 11\n    Birth date: 2000-02-28  Later date: 2011-03-01  Age: 11\n    Birth date: 2000-02-29  Later date: 2011-02-27  Age: 10\n    Birth date: 2000-02-29  Later date: 2011-02-28  Age: 11\n    Birth date: 2000-02-29  Later date: 2011-03-01  Age: 11\n    Birth date: 2000-03-01  Later date: 2011-02-27  Age: 10\n    Birth date: 2000-03-01  Later date: 2011-02-28  Age: 10\n    Birth date: 2000-03-01  Later date: 2011-03-01  Age: 11\n}\n</code></pre>\n\n<p>And for the later date 2012-02-28:</p>\n\n<pre><code>{\n    Birth date: 2000-02-28  Later date: 2012-02-28  Age: 12\n    Birth date: 2000-02-28  Later date: 2012-02-29  Age: 12\n    Birth date: 2000-02-28  Later date: 2012-03-01  Age: 12\n    Birth date: 2000-02-29  Later date: 2012-02-28  Age: 11\n    Birth date: 2000-02-29  Later date: 2012-02-29  Age: 12\n    Birth date: 2000-02-29  Later date: 2012-03-01  Age: 12\n    Birth date: 2000-03-01  Later date: 2012-02-28  Age: 11\n    Birth date: 2000-03-01  Later date: 2012-02-29  Age: 11\n    Birth date: 2000-03-01  Later date: 2012-03-01  Age: 12\n}\n</code></pre>\n'}, {'answer_id': 5229568, 'author': 'Doron', 'author_id': 649407, 'author_profile': 'https://Stackoverflow.com/users/649407', 'pm_score': 4, 'selected': False, 'text': '<p>How about this solution? </p>\n\n<pre><code>static string CalcAge(DateTime birthDay)\n{\n    DateTime currentDate = DateTime.Now;         \n    int approximateAge = currentDate.Year - birthDay.Year;\n    int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - \n        (currentDate.Month * 30 + currentDate.Day) ;\n\n    if (approximateAge == 0 || approximateAge == 1)\n    {                \n        int month =  Math.Abs(daysToNextBirthDay / 30);\n        int days = Math.Abs(daysToNextBirthDay % 30);\n\n        if (month == 0)\n            return "Your age is: " + daysToNextBirthDay + " days";\n\n        return "Your age is: " + month + " months and " + days + " days"; ;\n    }\n\n    if (daysToNextBirthDay &gt; 0)\n        return "Your age is: " + --approximateAge + " Years";\n\n    return "Your age is: " + approximateAge + " Years"; ;\n}\n</code></pre>\n'}, {'answer_id': 5623077, 'author': 'Marcel Toth', 'author_id': 702199, 'author_profile': 'https://Stackoverflow.com/users/702199', 'pm_score': 6, 'selected': False, 'text': '<p>2 Main problems to solve are:</p>\n\n<p><strong>1. Calculate Exact age</strong> - in years, months, days, etc.</p>\n\n<p><strong>2. Calculate Generally perceived age</strong> - people usually do not care how old they exactly are, they just care when their birthday in the current year is.</p>\n\n<hr>\n\n<p>Solution for <strong>1</strong> is obvious:</p>\n\n<pre><code>DateTime birth = DateTime.Parse("1.1.2000");\nDateTime today = DateTime.Today;     //we usually don\'t care about birth time\nTimeSpan age = today - birth;        //.NET FCL should guarantee this as precise\ndouble ageInDays = age.TotalDays;    //total number of days ... also precise\ndouble daysInYear = 365.2425;        //statistical value for 400 years\ndouble ageInYears = ageInDays / daysInYear;  //can be shifted ... not so precise\n</code></pre>\n\n<hr>\n\n<p>Solution for <strong>2</strong> is the one which is not so precise in determing total age, but is perceived as precise by people. People also usually use it, when they calculate their age "manually":</p>\n\n<pre><code>DateTime birth = DateTime.Parse("1.1.2000");\nDateTime today = DateTime.Today;\nint age = today.Year - birth.Year;    //people perceive their age in years\n\nif (today.Month &lt; birth.Month ||\n   ((today.Month == birth.Month) &amp;&amp; (today.Day &lt; birth.Day)))\n{\n  age--;  //birthday in current year not yet reached, we are 1 year younger ;)\n          //+ no birthday for 29.2. guys ... sorry, just wrong date for birth\n}\n</code></pre>\n\n<p>Notes to 2.:</p>\n\n<ul>\n<li>This is my preferred solution</li>\n<li>We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years</li>\n<li>I have put there little more lines for readability</li>\n</ul>\n\n<p>Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness:</p>\n\n<pre><code>public static int GetAge(DateTime bithDay, DateTime today) \n{ \n  //chosen solution method body\n}\n\npublic static int GetAge(DateTime birthDay) \n{ \n  return GetAge(birthDay, DateTime.Now);\n}\n</code></pre>\n'}, {'answer_id': 5989087, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': '<p>The following approach (extract from <a href="https://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET" rel="noreferrer">Time Period Library for .NET</a> class <em>DateDiff</em>) considers the calendar of the culture info:</p>\n\n<pre><code>// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2 )\n{\n  return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );\n} // YearDiff\n\n// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )\n{\n  if ( date1.Equals( date2 ) )\n  {\n    return 0;\n  }\n\n  int year1 = calendar.GetYear( date1 );\n  int month1 = calendar.GetMonth( date1 );\n  int year2 = calendar.GetYear( date2 );\n  int month2 = calendar.GetMonth( date2 );\n\n  // find the the day to compare\n  int compareDay = date2.Day;\n  int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );\n  if ( compareDay &gt; compareDaysPerMonth )\n  {\n    compareDay = compareDaysPerMonth;\n  }\n\n  // build the compare date\n  DateTime compareDate = new DateTime( year1, month2, compareDay,\n    date2.Hour, date2.Minute, date2.Second, date2.Millisecond );\n  if ( date2 &gt; date1 )\n  {\n    if ( compareDate &lt; date1 )\n    {\n      compareDate = compareDate.AddYears( 1 );\n    }\n  }\n  else\n  {\n    if ( compareDate &gt; date1 )\n    {\n      compareDate = compareDate.AddYears( -1 );\n    }\n  }\n  return year2 - calendar.GetYear( compareDate );\n} // YearDiff\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>// ----------------------------------------------------------------------\npublic void CalculateAgeSamples()\n{\n  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );\n  // &gt; Birthdate=29.02.2000, Age at 28.02.2009 is 8 years\n  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );\n  // &gt; Birthdate=29.02.2000, Age at 28.02.2012 is 11 years\n} // CalculateAgeSamples\n\n// ----------------------------------------------------------------------\npublic void PrintAge( DateTime birthDate, DateTime moment )\n{\n  Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );\n} // PrintAge\n</code></pre>\n'}, {'answer_id': 6075141, 'author': 'B2K', 'author_id': 763112, 'author_profile': 'https://Stackoverflow.com/users/763112', 'pm_score': 2, 'selected': False, 'text': '<p>Here\'s a DateTime extender that adds the age calculation to the DateTime object.</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static class AgeExtender\n{\n    public static int GetAge(this DateTime dt)\n    {\n        int d = int.Parse(dt.ToString("yyyyMMdd"));\n        int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));\n        return (t-d)/10000;\n    }\n}\n</code></pre>\n'}, {'answer_id': 6719204, 'author': 'cdiggins', 'author_id': 184528, 'author_profile': 'https://Stackoverflow.com/users/184528', 'pm_score': 3, 'selected': False, 'text': '<p>I\'ve made one small change to <a href="https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/1404#1404">Mark Soen\'s</a> answer: I\'ve rewriten the third line so that the expression can be parsed a bit more easily.</p>\n\n<pre><code>public int AgeInYears(DateTime bday)\n{\n    DateTime now = DateTime.Today;\n    int age = now.Year - bday.Year;            \n    if (bday.AddYears(age) &gt; now) \n        age--;\n    return age;\n}\n</code></pre>\n\n<p>I\'ve also made it into a function for the sake of clarity.</p>\n'}, {'answer_id': 7046204, 'author': 'Dylan Hayes', 'author_id': 892460, 'author_profile': 'https://Stackoverflow.com/users/892460', 'pm_score': 3, 'selected': False, 'text': '<p>I used ScArcher2\'s solution for an accurate Year calculation of a persons age but I needed to take it further and calculate their Months and Days along with the Years.</p>\n\n<pre><code>    public static Dictionary&lt;string,int&gt; CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)\n    {\n        //----------------------------------------------------------------------\n        // Can\'t determine age if we don\'t have a dates.\n        //----------------------------------------------------------------------\n        if (ndtBirthDate == null) return null;\n        if (ndtReferralDate == null) return null;\n\n        DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);\n        DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);\n\n        //----------------------------------------------------------------------\n        // Create our Variables\n        //----------------------------------------------------------------------\n        Dictionary&lt;string, int&gt; dYMD = new Dictionary&lt;string,int&gt;();\n        int iNowDate, iBirthDate, iYears, iMonths, iDays;\n        string sDif = "";\n\n        //----------------------------------------------------------------------\n        // Store off current date/time and DOB into local variables\n        //---------------------------------------------------------------------- \n        iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd"));\n        iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd"));\n\n        //----------------------------------------------------------------------\n        // Calculate Years\n        //----------------------------------------------------------------------\n        sDif = (iNowDate - iBirthDate).ToString();\n        iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));\n\n        //----------------------------------------------------------------------\n        // Store Years in Return Value\n        //----------------------------------------------------------------------\n        dYMD.Add("Years", iYears);\n\n        //----------------------------------------------------------------------\n        // Calculate Months\n        //----------------------------------------------------------------------\n        if (dtBirthDate.Month &gt; dtReferralDate.Month)\n            iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;\n        else\n            iMonths = dtBirthDate.Month - dtReferralDate.Month;\n\n        //----------------------------------------------------------------------\n        // Store Months in Return Value\n        //----------------------------------------------------------------------\n        dYMD.Add("Months", iMonths);\n\n        //----------------------------------------------------------------------\n        // Calculate Remaining Days\n        //----------------------------------------------------------------------\n        if (dtBirthDate.Day &gt; dtReferralDate.Day)\n            //Logic: Figure out the days in month previous to the current month, or the admitted month.\n            //       Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.\n            //       then take the referral date and simply add the number of days the person has lived this month.\n\n            //If referral date is january, we need to go back to the following year\'s December to get the days in that month.\n            if (dtReferralDate.Month == 1)\n                iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day;       \n            else\n                iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day;       \n        else\n            iDays = dtReferralDate.Day - dtBirthDate.Day;             \n\n        //----------------------------------------------------------------------\n        // Store Days in Return Value\n        //----------------------------------------------------------------------\n        dYMD.Add("Days", iDays);\n\n        return dYMD;\n}\n</code></pre>\n'}, {'answer_id': 8816564, 'author': 'Moshe L', 'author_id': 1056259, 'author_profile': 'https://Stackoverflow.com/users/1056259', 'pm_score': 2, 'selected': False, 'text': '<p>I want to add Hebrew calendar calculations (or other System.Globalization calendar can be used in the same way),  using rewrited functions from this thread:</p>\n\n<pre class="lang-cs prettyprint-override"><code>Public Shared Function CalculateAge(BirthDate As DateTime) As Integer\n    Dim HebCal As New System.Globalization.HebrewCalendar ()\n    Dim now = DateTime.Now()\n    Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)\n    Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)\n    If iNowMonth &lt; iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) &lt; HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1\n    Return iAge\nEnd Function\n</code></pre>\n'}, {'answer_id': 9431192, 'author': 'musefan', 'author_id': 838807, 'author_profile': 'https://Stackoverflow.com/users/838807', 'pm_score': 3, 'selected': False, 'text': '<p>This is simple and appears to be accurate for my needs. I am making an assumption for the purpose of leap years that regardless of when the person chooses to celebrate the birthday they are not technically a year older until 365 days have passed since their last birthday (i.e 28th February does not make them a year older).</p>\n<pre><code>DateTime now = DateTime.Today;\nDateTime birthday = new DateTime(1991, 02, 03);//3rd feb\n\nint age = now.Year - birthday.Year;\n\nif (now.Month &lt; birthday.Month || (now.Month == birthday.Month &amp;&amp; now.Day &lt; birthday.Day))//not had bday this year yet\n  age--;\n\nreturn age;\n</code></pre>\n'}, {'answer_id': 11328202, 'author': 'Narasimha', 'author_id': 254790, 'author_profile': 'https://Stackoverflow.com/users/254790', 'pm_score': 2, 'selected': False, 'text': '<p>Try this solution, it\'s working.</p>\n\n<pre class="lang-cs prettyprint-override"><code>int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - \n           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;\n</code></pre>\n'}, {'answer_id': 13531544, 'author': 'flindeberg', 'author_id': 691294, 'author_profile': 'https://Stackoverflow.com/users/691294', 'pm_score': 4, 'selected': False, 'text': '<p>This is not a direct answer, but more of a philosophical reasoning about the problem at hand from a quasi-scientific point of view.</p>\n\n<p>I would argue that the question does not specify the unit nor culture in which to measure age, most answers seem to assume an integer annual representation. The SI-unit for time is <code>second</code>, ergo the correct generic answer should be (of course assuming normalized <code>DateTime</code> and taking no regard whatsoever to relativistic effects):</p>\n\n<pre><code>var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;\n</code></pre>\n\n<p>In the Christian way of calculating age in years:</p>\n\n<pre><code>var then = ... // Then, in this case the birthday\nvar now = DateTime.UtcNow;\nint age = now.Year - then.Year;\nif (now.AddYears(-age) &lt; then) age--;\n</code></pre>\n\n<p>In finance there is a similar problem when calculating something often referred to as the <em>Day Count Fraction</em>, which roughly is a number of years for a given period. And the age issue is really a time measuring issue.</p>\n\n<p>Example for the actual/actual (counting all days "correctly") convention:</p>\n\n<pre><code>DateTime start, end = .... // Whatever, assume start is before end\n\ndouble startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);\ndouble endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);\ndouble middleContribution = (double) (end.Year - start.Year - 1);\n\ndouble DCF = startYearContribution + endYearContribution + middleContribution;\n</code></pre>\n\n<p>Another quite common way to measure time generally is by "serializing" (the dude who named this date convention must seriously have been trippin\'):</p>\n\n<pre><code>DateTime start, end = .... // Whatever, assume start is before end\nint days = (end - start).Days;\n</code></pre>\n\n<p>I wonder how long we have to go before a relativistic age in seconds becomes more useful than the rough approximation of earth-around-sun-cycles during one\'s lifetime so far :) Or in other words, when a period must be given a location or a function representing motion for itself to be valid :)</p>\n'}, {'answer_id': 13645039, 'author': 'rockXrock', 'author_id': 1254006, 'author_profile': 'https://Stackoverflow.com/users/1254006', 'pm_score': 4, 'selected': False, 'text': '<p>Do we need to consider people who is smaller than 1 year? as Chinese culture, we describe small babies\' age as 2 months or 4 weeks. </p>\n\n<p>Below is my implementation, it is not as simple as what I imagined, especially to deal with date like 2/28. </p>\n\n<pre><code>public static string HowOld(DateTime birthday, DateTime now)\n{\n    if (now &lt; birthday)\n        throw new ArgumentOutOfRangeException("birthday must be less than now.");\n\n    TimeSpan diff = now - birthday;\n    int diffDays = (int)diff.TotalDays;\n\n    if (diffDays &gt; 7)//year, month and week\n    {\n        int age = now.Year - birthday.Year;\n\n        if (birthday &gt; now.AddYears(-age))\n            age--;\n\n        if (age &gt; 0)\n        {\n            return age + (age &gt; 1 ? " years" : " year");\n        }\n        else\n        {// month and week\n            DateTime d = birthday;\n            int diffMonth = 1;\n\n            while (d.AddMonths(diffMonth) &lt;= now)\n            {\n                diffMonth++;\n            }\n\n            age = diffMonth-1;\n\n            if (age == 1 &amp;&amp; d.Day &gt; now.Day)\n                age--;\n\n            if (age &gt; 0)\n            {\n                return age + (age &gt; 1 ? " months" : " month");\n            }\n            else\n            {\n                age = diffDays / 7;\n                return age + (age &gt; 1 ? " weeks" : " week");\n            }\n        }\n    }\n    else if (diffDays &gt; 0)\n    {\n        int age = diffDays;\n        return age + (age &gt; 1 ? " days" : " day");\n    }\n    else\n    {\n        int age = diffDays;\n        return "just born";\n    }\n}\n</code></pre>\n\n<p>This implementation has passed below test cases.</p>\n\n<pre><code>[TestMethod]\npublic void TestAge()\n{\n    string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("1 year", age);\n\n    age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));\n    Assert.AreEqual("1 year", age);\n\n    age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("11 years", age);\n\n    age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("10 months", age);\n\n    age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("11 months", age);\n\n    age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("1 month", age);\n\n    age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));\n    Assert.AreEqual("1 year", age);\n\n    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));\n    Assert.AreEqual("11 months", age);\n\n    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));\n    Assert.AreEqual("1 year", age);\n\n    age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));\n    Assert.AreEqual("1 month", age);\n\n    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n    Assert.AreEqual("1 month", age);\n\n    // NOTE.\n    // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);\n    // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);\n    age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));\n    Assert.AreEqual("4 weeks", age);\n\n    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));\n    Assert.AreEqual("3 weeks", age);\n\n    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n    Assert.AreEqual("1 month", age);\n\n    age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));\n    Assert.AreEqual("3 weeks", age);\n\n    age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));\n    Assert.AreEqual("4 weeks", age);\n\n    age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));\n    Assert.AreEqual("1 week", age);\n\n    age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));\n    Assert.AreEqual("5 days", age);\n\n    age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));\n    Assert.AreEqual("1 day", age);\n\n    age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));\n    Assert.AreEqual("just born", age);\n\n    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));\n    Assert.AreEqual("8 years", age);\n\n    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));\n    Assert.AreEqual("9 years", age);\n\n    Exception e = null;\n\n    try\n    {\n        age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));\n    }\n    catch (ArgumentOutOfRangeException ex)\n    {\n        e = ex;\n    }\n\n    Assert.IsTrue(e != null);\n}\n</code></pre>\n\n<p>Hope it\'s helpful.</p>\n'}, {'answer_id': 14125249, 'author': 'Stranger', 'author_id': 1462452, 'author_profile': 'https://Stackoverflow.com/users/1462452', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a very simple and easy to follow example. </p>\n\n<pre><code>private int CalculateAge()\n{\n//get birthdate\n   DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);\n   int byear = dtBirth.Year;\n   int bmonth = dtBirth.Month;\n   int bday = dtBirth.Day;\n   DateTime dtToday = DateTime.Now;\n   int tYear = dtToday.Year;\n   int tmonth = dtToday.Month;\n   int tday = dtToday.Day;\n   int age = tYear - byear;\n   if (bmonth &lt; tmonth)\n       age--;\n   else if (bmonth == tmonth &amp;&amp; bday&gt;tday)\n   {\n       age--;\n   }\nreturn age;\n}\n</code></pre>\n'}, {'answer_id': 16142434, 'author': 'Matthew Watson', 'author_id': 106159, 'author_profile': 'https://Stackoverflow.com/users/106159', 'pm_score': 5, 'selected': False, 'text': '<p>Here\'s yet another answer:</p>\n<pre><code>public static int AgeInYears(DateTime birthday, DateTime today)\n{\n    return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;\n}\n</code></pre>\n<p>This has been extensively unit-tested. It does look a bit &quot;magic&quot;. The number 372 is the number of days there would be in a year if every month had 31 days.</p>\n<p>The explanation of why it works (<a href="https://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/ba4a98af-aab3-4c59-bdee-611334e502f2" rel="noreferrer">lifted from here</a>) is:</p>\n<blockquote>\n<p>Let\'s set <code>Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day</code></p>\n<p><code>age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372</code></p>\n<p>We know that what we need is either <code>Yn-Yb</code> if the date has already been reached, <code>Yn-Yb-1</code> if it has not.</p>\n<p>a) If <code>Mn&lt;Mb</code>, we have <code>-341 &lt;= 31*(Mn-Mb) &lt;= -31 and -30 &lt;= Dn-Db &lt;= 30</code></p>\n<p><code>-371 &lt;= 31*(Mn - Mb) + (Dn - Db) &lt;= -1</code></p>\n<p>With integer division</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = -1</code></p>\n<p>b) If <code>Mn=Mb</code> and <code>Dn&lt;Db</code>, we have <code>31*(Mn - Mb) = 0 and -30 &lt;= Dn-Db &lt;= -1</code></p>\n<p>With integer division, again</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = -1</code></p>\n<p>c) If <code>Mn&gt;Mb</code>, we have <code>31 &lt;= 31*(Mn-Mb) &lt;= 341 and -30 &lt;= Dn-Db &lt;= 30</code></p>\n<p><code>1 &lt;= 31*(Mn - Mb) + (Dn - Db) &lt;= 371</code></p>\n<p>With integer division</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n<p>d) If <code>Mn=Mb</code> and <code>Dn&gt;Db</code>, we have <code>31*(Mn - Mb) = 0 and 1 &lt;= Dn-Db &lt;= 3</code>0</p>\n<p>With integer division, again</p>\n<p><code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n<p>e) If <code>Mn=Mb</code> and <code>Dn=Db</code>, we have <code>31*(Mn - Mb) + Dn-Db = 0</code></p>\n<p>and therefore <code>(31*(Mn - Mb) + (Dn - Db)) / 372 = 0</code></p>\n</blockquote>\n'}, {'answer_id': 18682920, 'author': 'vulcan raven', 'author_id': 863980, 'author_profile': 'https://Stackoverflow.com/users/863980', 'pm_score': 2, 'selected': False, 'text': '<p>With fewer conversions and UtcNow, this code can take care of someone born on the Feb 29 in a leap year:</p>\n\n<pre><code>public int GetAge(DateTime DateOfBirth)\n{\n    var Now = DateTime.UtcNow;\n    return Now.Year - DateOfBirth.Year -\n        (\n            (\n                Now.Month &gt; DateOfBirth.Month ||\n                (Now.Month == DateOfBirth.Month &amp;&amp; Now.Day &gt;= DateOfBirth.Day)\n            ) ? 0 : 1\n        );\n}\n</code></pre>\n'}, {'answer_id': 18895699, 'author': 'Archit', 'author_id': 2435287, 'author_profile': 'https://Stackoverflow.com/users/2435287', 'pm_score': 1, 'selected': False, 'text': '<blockquote>\n  <p>How come the MSDN help did not tell you that? It looks so obvious:</p>\n</blockquote>\n\n<pre class="lang-cs prettyprint-override"><code>System.DateTime birthTime = AskTheUser(myUser); // :-)\nSystem.DateTime now = System.DateTime.Now;\nSystem.TimeSpan age = now - birthTime; // As simple as that\ndouble ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?\n</code></pre>\n'}, {'answer_id': 18898663, 'author': 'Dakotah Hicock', 'author_id': 1226335, 'author_profile': 'https://Stackoverflow.com/users/1226335', 'pm_score': 4, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>TimeSpan diff = DateTime.Now - birthdayDateTime;\nstring age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);\n</code></pre>\n\n<p>I\'m not sure how exactly you\'d like it returned to you, so I just made a readable string.</p>\n'}, {'answer_id': 18924226, 'author': 'Jacqueline Loriault', 'author_id': 2778315, 'author_profile': 'https://Stackoverflow.com/users/2778315', 'pm_score': 5, 'selected': False, 'text': '<p>This gives "more detail" to this question. Maybe this is what you\'re looking for</p>\n\n<pre><code>DateTime birth = new DateTime(1974, 8, 29);\nDateTime today = DateTime.Now;\nTimeSpan span = today - birth;\nDateTime age = DateTime.MinValue + span;\n\n// Make adjustment due to MinValue equalling 1/1/1\nint years = age.Year - 1;\nint months = age.Month - 1;\nint days = age.Day - 1;\n\n// Print out not only how many years old they are but give months and days as well\nConsole.Write("{0} years, {1} months, {2} days", years, months, days);\n</code></pre>\n'}, {'answer_id': 20348258, 'author': 'Dhaval Panchal', 'author_id': 2368967, 'author_profile': 'https://Stackoverflow.com/users/2368967', 'pm_score': -1, 'selected': False, 'text': '<p>To calculate the age with nearest age:</p>\n\n<pre class="lang-cs prettyprint-override"><code>var ts = DateTime.Now - new DateTime(1988, 3, 19);\nvar age = Math.Round(ts.Days / 365.0);\n</code></pre>\n'}, {'answer_id': 20715576, 'author': 'Matt Johnson-Pint', 'author_id': 634824, 'author_profile': 'https://Stackoverflow.com/users/634824', 'pm_score': 4, 'selected': False, 'text': '<p>This classic question is deserving of a <a href="https://nodatime.org" rel="noreferrer">Noda Time</a> solution.</p>\n\n<pre><code>static int GetAge(LocalDate dateOfBirth)\n{\n    Instant now = SystemClock.Instance.Now;\n\n    // The target time zone is important.\n    // It should align with the *current physical location* of the person\n    // you are talking about.  When the whereabouts of that person are unknown,\n    // then you use the time zone of the person who is *asking* for the age.\n    // The time zone of birth is irrelevant!\n\n    DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];\n\n    LocalDate today = now.InZone(zone).Date;\n\n    Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);\n\n    return (int) period.Years;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>LocalDate dateOfBirth = new LocalDate(1976, 8, 27);\nint age = GetAge(dateOfBirth);\n</code></pre>\n\n<p>You might also be interested in the following improvements:</p>\n\n<ul>\n<li><p>Passing in the clock as an <code>IClock</code>, instead of using <code>SystemClock.Instance</code>, would improve testability.</p></li>\n<li><p>The target time zone will likely change, so you\'d want a <code>DateTimeZone</code> parameter as well.</p></li>\n</ul>\n\n<p>See also my blog post on this subject: <a href="https://codeofmatt.com/2014/04/09/handling-birthdays-and-other-anniversaries/" rel="noreferrer">Handling Birthdays, and Other Anniversaries</a></p>\n'}, {'answer_id': 21276626, 'author': 'DareDevil', 'author_id': 1147352, 'author_profile': 'https://Stackoverflow.com/users/1147352', 'pm_score': 4, 'selected': False, 'text': '<p>I have a customized method to calculate age, plus a bonus validation message just in case it helps:</p>\n\n<pre><code>public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)\n{\n    years = 0;\n    months = 0;\n    days = 0;\n\n    DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);\n    DateTime tmpnow = new DateTime(now.Year, now.Month, 1);\n\n    while (tmpdob.AddYears(years).AddMonths(months) &lt; tmpnow)\n    {\n        months++;\n        if (months &gt; 12)\n        {\n            years++;\n            months = months - 12;\n        }\n    }\n\n    if (now.Day &gt;= dob.Day)\n        days = days + now.Day - dob.Day;\n    else\n    {\n        months--;\n        if (months &lt; 0)\n        {\n            years--;\n            months = months + 12;\n        }\n        days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;\n    }\n\n    if (DateTime.IsLeapYear(dob.Year) &amp;&amp; dob.Month == 2 &amp;&amp; dob.Day == 29 &amp;&amp; now &gt;= new DateTime(now.Year, 3, 1))\n        days++;\n\n}   \n\nprivate string ValidateDate(DateTime dob) //This method will validate the date\n{\n    int Years = 0; int Months = 0; int Days = 0;\n\n    GetAge(dob, DateTime.Now, out Years, out Months, out Days);\n\n    if (Years &lt; 18)\n        message =  Years + " is too young. Please try again on your 18th birthday.";\n    else if (Years &gt;= 65)\n        message = Years + " is too old. Date of Birth must not be 65 or older.";\n    else\n        return null; //Denotes validation passed\n}\n</code></pre>\n\n<p>Method call here and pass out datetime value (MM/dd/yyyy if server set to USA locale). Replace this with anything a messagebox or any container to display:</p>\n\n<pre><code>DateTime dob = DateTime.Parse("03/10/1982");  \n\nstring message = ValidateDate(dob);\n\nlbldatemessage.Visible = !StringIsNullOrWhitespace(message);\nlbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string\n</code></pre>\n\n<p>Remember you can format the message any way you like.</p>\n'}, {'answer_id': 25014539, 'author': 'Pratik Bhoir', 'author_id': 2772550, 'author_profile': 'https://Stackoverflow.com/users/2772550', 'pm_score': -1, 'selected': False, 'text': '<p>A one-liner answer:</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");\nvar age = ((DateTime.Now - dateOfBirth).Days) / 365;\n</code></pre>\n'}, {'answer_id': 26529035, 'author': 'mjb', 'author_id': 520848, 'author_profile': 'https://Stackoverflow.com/users/520848', 'pm_score': 4, 'selected': False, 'text': '<p>This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.</p>\n\n<pre class="lang-cs prettyprint-override"><code>public int GetAge(DateTime birthDate)\n{\n    int age = DateTime.Now.Year - birthDate.Year;\n\n    if (birthDate.DayOfYear &gt; DateTime.Now.DayOfYear)\n        age--;\n\n    return age;\n}\n\n\n\n\n</code></pre>\n'}, {'answer_id': 28567336, 'author': 'dav_i', 'author_id': 1185053, 'author_profile': 'https://Stackoverflow.com/users/1185053', 'pm_score': 2, 'selected': False, 'text': '<p>Just because I don\'t think the top answer is that clear:</p>\n\n<pre class="lang-cs prettyprint-override"><code>public static int GetAgeByLoop(DateTime birthday)\n{\n    var age = -1;\n\n    for (var date = birthday; date &lt; DateTime.Today; date = date.AddYears(1))\n    {\n        age++;\n    }\n\n    return age;\n}\n</code></pre>\n'}, {'answer_id': 30145502, 'author': 'mind_overflow', 'author_id': 3889784, 'author_profile': 'https://Stackoverflow.com/users/3889784', 'pm_score': -1, 'selected': False, 'text': '<p>Check this out:</p>\n\n<pre class="lang-cs prettyprint-override"><code>TimeSpan ts = DateTime.Now.Subtract(Birthdate);\nage = (byte)(ts.TotalDays / 365.25);\n</code></pre>\n'}, {'answer_id': 31025282, 'author': 'user1210708', 'author_id': 1210708, 'author_profile': 'https://Stackoverflow.com/users/1210708', 'pm_score': 2, 'selected': False, 'text': '<p>Here is a function that is serving me well. No calculations , very simple.</p>\n<pre><code>    public static string ToAge(this DateTime dob, DateTime? toDate = null)\n    {\n        if (!toDate.HasValue)\n            toDate = DateTime.Now;\n        var now = toDate.Value;\n\n        if (now.CompareTo(dob) &lt; 0)\n            return &quot;Future date&quot;;\n\n        int years = now.Year - dob.Year;\n        int months = now.Month - dob.Month;\n        int days = now.Day - dob.Day;\n\n        if (days &lt; 0)\n        {\n            months--;\n            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;\n        }\n\n        if (months &lt; 0)\n        {\n            years--;\n            months = 12 + months;\n        }\n\n\n        return string.Format(&quot;{0} year(s), {1} month(s), {2} days(s)&quot;,\n            years,\n            months,\n            days);\n    }\n</code></pre>\n<p>And here is a unit test:</p>\n<pre><code>    [Test]\n    public void ToAgeTests()\n    {\n        var date = new DateTime(2000, 1, 1);\n        Assert.AreEqual(&quot;0 year(s), 0 month(s), 1 days(s)&quot;, new DateTime(1999, 12, 31).ToAge(date));\n        Assert.AreEqual(&quot;0 year(s), 0 month(s), 0 days(s)&quot;, new DateTime(2000, 1, 1).ToAge(date));\n        Assert.AreEqual(&quot;1 year(s), 0 month(s), 0 days(s)&quot;, new DateTime(1999, 1, 1).ToAge(date));\n        Assert.AreEqual(&quot;0 year(s), 11 month(s), 0 days(s)&quot;, new DateTime(1999, 2, 1).ToAge(date));\n        Assert.AreEqual(&quot;0 year(s), 10 month(s), 25 days(s)&quot;, new DateTime(1999, 2, 4).ToAge(date));\n        Assert.AreEqual(&quot;0 year(s), 10 month(s), 1 days(s)&quot;, new DateTime(1999, 2, 28).ToAge(date));\n\n        date = new DateTime(2000, 2, 15);\n        Assert.AreEqual(&quot;0 year(s), 0 month(s), 28 days(s)&quot;, new DateTime(2000, 1, 18).ToAge(date));\n    }\n</code></pre>\n'}, {'answer_id': 31077562, 'author': 'Lukas', 'author_id': 593388, 'author_profile': 'https://Stackoverflow.com/users/593388', 'pm_score': 3, 'selected': False, 'text': '<p>It can be this simple:</p>\n\n<pre class="lang-cs prettyprint-override"><code>int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;\n</code></pre>\n'}, {'answer_id': 31178328, 'author': 'BrunoVT', 'author_id': 4090831, 'author_profile': 'https://Stackoverflow.com/users/4090831', 'pm_score': 2, 'selected': False, 'text': '<p>I would simply do this:</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime birthDay = new DateTime(1990, 05, 23);\nDateTime age = DateTime.Now - birthDay;\n</code></pre>\n\n<p>This way you can calculate the exact age of a person, down to the millisecond if you want.</p>\n'}, {'answer_id': 32954095, 'author': 'VhsPiceros', 'author_id': 581783, 'author_profile': 'https://Stackoverflow.com/users/581783', 'pm_score': 2, 'selected': False, 'text': '<p>I have used the following for this issue. I know it\'s not very elegant, but it\'s working.</p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime zeroTime = new DateTime(1, 1, 1);\nvar date1 = new DateTime(1983, 03, 04);\nvar date2 = DateTime.Now;\nvar dif = date2 - date1;\nint years = (zeroTime + dif).Year - 1;\nLog.DebugFormat("Years --&gt;{0}", years);\n</code></pre>\n'}, {'answer_id': 33082044, 'author': 'Ahmed Sabry', 'author_id': 4707576, 'author_profile': 'https://Stackoverflow.com/users/4707576', 'pm_score': 2, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>public string GetAge(this DateTime birthdate, string ageStrinFormat = null)\n{\n    var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);\n    return string.Format(ageStrinFormat ?? "{0}/{1}/{2}",\n        (date.Year - birthdate.Year), date.Month, date.Day);\n}\n</code></pre>\n'}, {'answer_id': 36893577, 'author': 'CathalMF', 'author_id': 1680271, 'author_profile': 'https://Stackoverflow.com/users/1680271', 'pm_score': 3, 'selected': False, 'text': '<p>This is the easiest way to answer this in a single line.</p>\n<pre class="lang-cs prettyprint-override"><code>DateTime Dob = DateTime.Parse(&quot;1985-04-24&quot;);\n \nint Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1;\n</code></pre>\n<p>This also works for leap years.</p>\n'}, {'answer_id': 37022367, 'author': 'John Jang', 'author_id': 3634867, 'author_profile': 'https://Stackoverflow.com/users/3634867', 'pm_score': 3, 'selected': False, 'text': '<p>=== <strong>Common Saying (from months to years old)</strong> ===</p>\n\n<p>If you just for common use, here is the code as your information:</p>\n\n<pre><code>DateTime today = DateTime.Today;\nDateTime bday = DateTime.Parse("2016-2-14");\nint age = today.Year - bday.Year;\nvar unit = "";\n\nif (bday &gt; today.AddYears(-age))\n{\n    age--;\n}\nif (age == 0)   // Under one year old\n{\n    age = today.Month - bday.Month;\n\n    age = age &lt;= 0 ? (12 + age) : age;  // The next year before birthday\n\n    age = today.Day - bday.Day &gt;= 0 ? age : --age;  // Before the birthday.day\n\n    unit = "month";\n}\nelse {\n    unit = "year";\n}\n\nif (age &gt; 1)\n{\n    unit = unit + "s";\n}\n</code></pre>\n\n<p>The test result as below:</p>\n\n<pre><code>The birthday: 2016-2-14\n\n2016-2-15 =&gt;  age=0, unit=month;\n2016-5-13 =&gt;  age=2, unit=months;\n2016-5-14 =&gt;  age=3, unit=months; \n2016-6-13 =&gt;  age=3, unit=months; \n2016-6-15 =&gt;  age=4, unit=months; \n2017-1-13 =&gt;  age=10, unit=months; \n2017-1-14 =&gt;  age=11, unit=months; \n2017-2-13 =&gt;  age=11, unit=months; \n2017-2-14 =&gt;  age=1, unit=year; \n2017-2-15 =&gt;  age=1, unit=year; \n2017-3-13 =&gt;  age=1, unit=year;\n2018-1-13 =&gt;  age=1, unit=year; \n2018-1-14 =&gt;  age=1, unit=year; \n2018-2-13 =&gt;  age=1, unit=year; \n2018-2-14 =&gt;  age=2, unit=years; \n</code></pre>\n'}, {'answer_id': 38121726, 'author': 'xenedia', 'author_id': 836565, 'author_profile': 'https://Stackoverflow.com/users/836565', 'pm_score': 3, 'selected': False, 'text': "<p>SQL version:</p>\n\n<pre><code>declare @dd smalldatetime = '1980-04-01'\ndeclare @age int = YEAR(GETDATE())-YEAR(@dd)\nif (@dd&gt; DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1\n\nprint @age  \n</code></pre>\n"}, {'answer_id': 39779195, 'author': 'André Sobreiro', 'author_id': 3177959, 'author_profile': 'https://Stackoverflow.com/users/3177959', 'pm_score': 3, 'selected': False, 'text': '<p>Wow, I had to give my answer here... There are so many answers for such a simple question.</p>\n\n<pre><code>private int CalcularIdade(DateTime dtNascimento)\n    {\n        var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd"));\n        var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd"));\n\n        double diff = (nHoje - nAniversario) / 10000;\n\n        var ret = Convert.ToInt32(Math.Truncate(diff));\n\n        return ret;\n    }\n</code></pre>\n'}, {'answer_id': 40196001, 'author': 'K1laba', 'author_id': 1591350, 'author_profile': 'https://Stackoverflow.com/users/1591350', 'pm_score': 3, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>private int GetYearDiff(DateTime start, DateTime end)\n{\n    int diff = end.Year - start.Year;\n    if (end.DayOfYear &lt; start.DayOfYear) { diff -= 1; }\n    return diff;\n}\n[Fact]\npublic void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()\n{\n    //arrange\n    var now = DateTime.Now;\n    //act\n    //assert\n    Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed\n    Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed\n    Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed\n}\n</code></pre>\n'}, {'answer_id': 45127603, 'author': 'Sean Kearon', 'author_id': 2608, 'author_profile': 'https://Stackoverflow.com/users/2608', 'pm_score': 2, 'selected': False, 'text': '<p>I often count on my fingers. I need to look at a calendar to work out when things change. So that\'s what I\'d do in my code:</p>\n\n<pre><code>int AgeNow(DateTime birthday)\n{\n    return AgeAt(DateTime.Now, birthday);\n}\n\nint AgeAt(DateTime now, DateTime birthday)\n{\n    return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);\n}\n\nint AgeAt(DateTime now, DateTime birthday, Calendar calendar)\n{\n    // My age has increased on the morning of my\n    // birthday even though I was born in the evening.\n    now = now.Date;\n    birthday = birthday.Date;\n\n    var age = 0;\n    if (now &lt;= birthday) return age; // I am zero now if I am to be born tomorrow.\n\n    while (calendar.AddYears(birthday, age + 1) &lt;= now)\n    {\n        age++;\n    }\n    return age;\n}\n</code></pre>\n\n<p>Running this through in <a href="https://en.wikipedia.org/wiki/LINQPad" rel="nofollow noreferrer">LINQPad</a> gives this:</p>\n\n<pre><code>PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968\nPASSED: someone born on 29 February 1964 is age 3 on 28 February 1968\nPASSED: someone born on 31 December 2016 is age 0 on 01 January 2017\n</code></pre>\n\n<p>Code in LINQPad is <a href="http://share.linqpad.net/3gx8ba.linq" rel="nofollow noreferrer">here</a>.</p>\n'}, {'answer_id': 46968983, 'author': 'Sunny Jangid', 'author_id': 6803066, 'author_profile': 'https://Stackoverflow.com/users/6803066', 'pm_score': 2, 'selected': False, 'text': '<p>Simple Code</p>\n\n<pre><code> var birthYear=1993;\n var age = DateTime.Now.AddYears(-birthYear).Year;\n</code></pre>\n'}, {'answer_id': 47035067, 'author': 'Kaval Patel', 'author_id': 6629154, 'author_profile': 'https://Stackoverflow.com/users/6629154', 'pm_score': 0, 'selected': False, 'text': '<p>To calculate how many years old a person is, </p>\n\n<pre class="lang-cs prettyprint-override"><code>DateTime dateOfBirth;\n\nint ageInYears = DateTime.Now.Year - dateOfBirth.Year;\n\nif (dateOfBirth &gt; today.AddYears(-ageInYears )) ageInYears --;\n</code></pre>\n'}, {'answer_id': 47837162, 'author': 'Moises Conejo', 'author_id': 4155324, 'author_profile': 'https://Stackoverflow.com/users/4155324', 'pm_score': 2, 'selected': False, 'text': '<p>Just use:</p>\n\n<pre class="lang-cs prettyprint-override"><code>(DateTime.Now - myDate).TotalHours / 8766.0\n</code></pre>\n\n<p>The current date - <code>myDate = TimeSpan</code>, get total hours and divide in the total hours per year and get exactly the age/months/days...</p>\n'}, {'answer_id': 48688691, 'author': 'wild coder', 'author_id': 9106094, 'author_profile': 'https://Stackoverflow.com/users/9106094', 'pm_score': 2, 'selected': False, 'text': "<p>Here is the simplest way to calculate someone's age.<br>\nCalculating someone's age is pretty straightforward, and here's how! In order for the code to work, you need a DateTime object called BirthDate containing the birthday.  </p>\n\n<pre><code> C#\n        // get the difference in years\n        int years = DateTime.Now.Year - BirthDate.Year; \n        // subtract another year if we're before the\n        // birth day in the current year\n        if (DateTime.Now.Month &lt; BirthDate.Month || \n            (DateTime.Now.Month == BirthDate.Month &amp;&amp; \n            DateTime.Now.Day &lt; BirthDate.Day)) \n            years--;\n  VB.NET\n        ' get the difference in years\n        Dim years As Integer = DateTime.Now.Year - BirthDate.Year\n        ' subtract another year if we're before the\n        ' birth day in the current year\n        If DateTime.Now.Month &lt; BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day &lt; BirthDate.Day) Then \n            years = years - 1\n        End If\n</code></pre>\n"}, {'answer_id': 48805951, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<pre class="lang-cs prettyprint-override"><code>var birthDate = ... // DOB\nvar resultDate = DateTime.Now - birthDate;\n</code></pre>\n\n<p>Using <code>resultDate</code> you can apply <code>TimeSpan</code> properties whatever you want to display it.</p>\n'}, {'answer_id': 60541141, 'author': 'Alexander', 'author_id': 11841521, 'author_profile': 'https://Stackoverflow.com/users/11841521', 'pm_score': 0, 'selected': False, 'text': '<p>Very simple answer</p>\n\n<pre><code>        DateTime dob = new DateTime(1991, 3, 4); \n        DateTime now = DateTime.Now; \n        int dobDay = dob.Day, dobMonth = dob.Month; \n        int add = -1; \n        if (dobMonth &lt; now.Month)\n        {\n            add = 0;\n        }\n        else if (dobMonth == now.Month)\n        {\n            if(dobDay &lt;= now.Day)\n            {\n                add = 0;\n            }\n            else\n            {\n                add = -1;\n            }\n        }\n        else\n        {\n            add = -1;\n        } \n        int age = now.Year - dob.Year + add;\n</code></pre>\n'}, {'answer_id': 64085367, 'author': 'Alexander Díaz', 'author_id': 11120141, 'author_profile': 'https://Stackoverflow.com/users/11120141', 'pm_score': 0, 'selected': False, 'text': '<pre><code>int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;\nConsole.WriteLine(&quot;Age {0}&quot;, Age);\n</code></pre>\n'}, {'answer_id': 64135345, 'author': 'Abrar Jahin', 'author_id': 2193439, 'author_profile': 'https://Stackoverflow.com/users/2193439', 'pm_score': -1, 'selected': False, 'text': '<p>I think this problem can be solved with an easier way like this-</p>\n<p>The class can be like-</p>\n<pre><code>using System;\n\nnamespace TSA\n{\n    class BirthDay\n    {\n        double ageDay;\n        public BirthDay(int day, int month, int year)\n        {\n            DateTime birthDate = new DateTime(year, month, day);\n            ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow\n        }\n\n        internal int GetAgeYear()\n        {\n            return (int)Math.Truncate(ageDay / 365);\n        }\n\n        internal int GetAgeMonth()\n        {\n            return (int)Math.Truncate((ageDay % 365) / 30);\n        }\n    }\n}\n</code></pre>\n<p>And calls can be like-</p>\n<pre><code>BirthDay b = new BirthDay(1,12,1990);\nint year = b.GetAgeYear();\nint month = b.GetAgeMonth();\n</code></pre>\n'}, {'answer_id': 64220001, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I have no knowledge about <code>DateTime</code> but all I can do is this:</p>\n<pre><code>using System;\n                    \npublic class Program\n{\n    public static int getAge(int month, int day, int year) {\n        DateTime today = DateTime.Today;\n        int currentDay = today.Day;\n        int currentYear = today.Year;\n        int currentMonth = today.Month;\n        int age = 0;\n        if (currentMonth &lt; month) {\n            age -= 1;\n        } else if (currentMonth == month) {\n            if (currentDay &lt; day) {\n                age -= 1;\n            }\n        }\n        currentYear -= year;\n        age += currentYear;\n        return age;\n    }\n    public static void Main()\n    {\n        int ageInYears = getAge(8, 10, 2007);\n        Console.WriteLine(ageInYears);\n    }\n}\n</code></pre>\n<p>A little confusing, but looking at the code more carefully, it will all make sense.</p>\n'}, {'answer_id': 68783776, 'author': 'Wylan Osorio', 'author_id': 2249897, 'author_profile': 'https://Stackoverflow.com/users/2249897', 'pm_score': 0, 'selected': False, 'text': '<pre><code>var startDate = new DateTime(2015, 04, 05);//your start date\nvar endDate = DateTime.Now;\nvar years = 0;\nwhile(startDate &lt; endDate) \n{\n     startDate = startDate.AddYears(1);\n     if(startDate &lt; endDate) \n     {\n         years++;\n     }\n}\n</code></pre>\n'}, {'answer_id': 69123059, 'author': 'Rob', 'author_id': 3178666, 'author_profile': 'https://Stackoverflow.com/users/3178666', 'pm_score': 0, 'selected': False, 'text': "<p>One could compute 'age' (i.e. the 'westerner' way) this way:</p>\n<pre><code>public static int AgeInYears(this System.DateTime source, System.DateTime target)\n  =&gt; target.Year - source.Year is int age &amp;&amp; age &gt; 0 &amp;&amp; source.AddYears(age) &gt; target ? age - 1 : age &lt; 0 &amp;&amp; source.AddYears(age) &lt; target ? age + 1 : age;\n</code></pre>\n<p>If the direction of time is 'negative', the age will be negative also.</p>\n<p>One can add a fraction, which represents the amount of age accumulated from target to the next birthday:</p>\n<pre><code>public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)\n{\n  var sign = (source &lt;= target ? 1 : -1);\n\n  var ageInYears = AgeInYears(source, target); // The method above.\n\n  var last = source.AddYears(ageInYears);\n  var next = source.AddYears(ageInYears + sign);\n\n  var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;\n\n  return ageInYears + fractionalAge;\n}\n</code></pre>\n<p>The fraction is the ratio of passed time (from the last birthday) over total time (to the next birthday).</p>\n<p>Both of the methods work the same way whether going forward or backward in time.</p>\n"}, {'answer_id': 69308492, 'author': 'A.G.', 'author_id': 8261867, 'author_profile': 'https://Stackoverflow.com/users/8261867', 'pm_score': 2, 'selected': False, 'text': '<p>I would strongly recommend using a NuGet package called <a href="https://www.nuget.org/packages/AgeCalculator/" rel="nofollow noreferrer">AgeCalculator</a> since there are many things to consider when calculating age (leap years, time component etc) and only two lines of code does not cut it. The library gives you more than just a year. It even takes into consideration the time component at the calculation so you get an accurate age with years, months, days and time components. It is more advanced giving an option to consider Feb 29 in a leap year as Feb 28 in a non-leap year.</p>\n'}, {'answer_id': 69981159, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>This is a very simple approach:</p>\n<pre><code>int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;\n</code></pre>\n'}, {'answer_id': 70659202, 'author': 'Wouter', 'author_id': 4491768, 'author_profile': 'https://Stackoverflow.com/users/4491768', 'pm_score': 0, 'selected': False, 'text': '<p>A branchless solution:</p>\n<pre><code>public int GetAge(DateOnly birthDate, DateOnly today)\n{\n    return today.Year - birthDate.Year + (((today.Month &lt;&lt; 5) + today.Day - ((birthDate.Month &lt;&lt; 5) + birthDate.Day)) &gt;&gt; 31);\n}\n</code></pre>\n'}, {'answer_id': 71185870, 'author': 'subcoder', 'author_id': 8227155, 'author_profile': 'https://Stackoverflow.com/users/8227155', 'pm_score': 1, 'selected': False, 'text': '<p>Simple and readable with complementary method</p>\n<pre><code>public static int getAge(DateTime birthDate)\n{\n    var today = DateTime.Today;\n    var age = today.Year - birthDate.Year;\n    var monthDiff = today.Month - birthDate.Month;\n    var dayDiff = today.Day - birthDate.Day;\n\n    if (dayDiff &lt; 0)\n    {\n        monthDiff--;\n    }\n    if (monthDiff &lt; 0)\n    {\n       age--;\n    }\n    return age;\n}\n</code></pre>\n'}, {'answer_id': 73211429, 'author': 'Ruchir Gupta', 'author_id': 3832403, 'author_profile': 'https://Stackoverflow.com/users/3832403', 'pm_score': 0, 'selected': False, 'text': "<p>Don't know why nobody tried this:</p>\n<pre><code>        ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);\n</code></pre>\n<p>All it requires is <code>using Microsoft.VisualBasic;</code> and reference to this assembly in the project (if not already referred).</p>\n"}]
['https://Stackoverflow.com/questions/9', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1/']