2220

Given a DateTime representing a person's birthday, how do I calculate their age in years?

Okx
  • 353
  • 3
  • 23
Jeff Atwood
  • 63,320
  • 48
  • 150
  • 153
  • 188
    what all of the answers so far have missed is that it depends where the person was born and where they are right now. – Yaur May 21 '11 at 07:34
  • 54
    @Yaur: Just convert the time of now + birth into GMT/UTC, age is only a relative value, hence timezones are irrelevant. For determining the user's current timezone, you can use GeoLocating. – Stefan Steiger Oct 03 '11 at 10:20
  • 1
    Why not consider [Julian Date][1]? [1]: http://stackoverflow.com/questions/7103064/java-calculate-the-number-of-days-between-two-dates/14278129#14278129 – Muhammad Hewedy Oct 05 '13 at 13:32
  • 9
    If we're taking into consideration @Yaur 's suggestion of cross-timezone calculations, should Day Light Saving Time affect the calculation in any manner? – DDM Jul 11 '15 at 03:42
  • 4
    Note that for someone less than one year old, their age is given in days, weeks, or months. The transition time for the units may be domain-specific. – Andrew Morton Nov 10 '17 at 22:09
  • 6
    As we can all see there is no definitive definition of age. Many women I've met tends to round up their living time to a complete year until twenty-something, then they start rounding down. I was born Jan 3rd, so I just subtract current year from my birth year, no matter what day it is. some people think if you were born on a leap day, you age in 1/4 ratio. What if you were born on at a leap second? does an 8 months old baby counted as 1? If I fly to west, do I get younger? If my hearts stops for a minute, should I include that in calculation? – Erdogan Kurtur Oct 15 '20 at 16:27
  • 3
    A scenario all the answers fail to take into account: my Great Grandad was born 29th February 1928. He died the year before last, just 13 months short of his 23rd birthday. – Rab Jan 14 '21 at 17:03
  • 1
    @Rab -- generally speaking the age of someone born on leapyear is not claculated like that .... but the grammar above took a while to figure out. – JosephDoggie Feb 17 '21 at 16:56
  • It's amazing how difficult what should be a simple operation is! And the integer ages don't always come out to what one would expect either... – JosephDoggie Apr 15 '21 at 13:37
  • 1
    @Yaur, time zone is irrelevant calculating age since the dates provided should contain that information already. – A.G. Sep 24 '21 at 16:43
  • You're specifically asking about _international age_. Different cultures compute age differently, for example, Korean age - you start at 1 when you are born and you gain a year when the calendar year changes - not necessarily on your birthday. – Wyck Jun 21 '23 at 15:14

74 Answers74

2399

An easy to understand and simple solution.

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.

LopDev
  • 823
  • 10
  • 26
Mike Polen
  • 3,586
  • 1
  • 27
  • 31
  • 96
    This answer does not work with all locales and all ages. Several countries have skipped dates after the birth of current living people, including Russia (1918), Greece (1924) and Turkey (1926). – Lars D Nov 09 '09 at 22:09
  • 40
    Actually, it's still not entirely correct. This code presumes that 'bday' is the date-portion of a DateTime. It's an edge-case (I guess most people will just be passing dates and not date-times), but if you pass in a birthday as a date-and-time where the time is greater than 00:00:00 then you'll run into the bug Danvil pointed out. Setting bday = bday.Date fixes this. – Øyvind Nov 16 '10 at 15:37
  • 8
    this is 12 years but why don't you just minus brithday - today later go for timespan and you can get it without an if. – AbbathCL Mar 17 '21 at 06:19
  • 4
    @AbbathCl: Timespan has no years. – Wouter Jul 22 '22 at 10:20
  • 3
    Am I missing something here? I guess that the days are missing completely. When the person has birthday on 1st of August and you run the script on 31st of July you get the same result as when you run the script on 1st of August but the person is one year older. – M Stoerzel Sep 26 '22 at 13:03
  • 2
    I think the comment (mentioning leap years) is misleading. I guess the correct explanation would be: (1) if you were born in 1980 and it's 2022 then you WILL turn 42 somewhere in this year - so `int age = DateTime.Today.Year - dateOfBirth.Year`. (2) if your birthday hasn't arrived yet this year subtract one: `if (dateOfBirth.Date.AddYears(age) > DateTime.Today) age--` – drizin Dec 06 '22 at 15:45
  • 1
    I agree with drizin: The explanation could be clearer by changing `// Go back to the year in which the person was born in case of a leap year` to `// Go back to the year in which the person was born. if birthdate hasn't arrived yet, subtract one year. Also handles leap year` – Jim B Feb 01 '23 at 19:56
  • must be checked for a month, and date if birthdate is celebrated on that check year. Leap year has to do only if birthdate happened to be on feb 29 only!! – Sam Saarian Feb 02 '23 at 01:22
1109

This is a strange way to do it, but if you format the date to yyyymmdd and subtract the date of birth from the current date then drop the last 4 digits you've got the age :)

I don't know C#, but I believe this will work in any language.

20080814 - 19800703 = 280111 

Drop the last 4 digits = 28.

C# Code:

int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
int dob = int.Parse(dateOfBirth.ToString("yyyyMMdd"));
int age = (now - dob) / 10000;

Or alternatively without all the type conversion in the form of an extension method. Error checking omitted:

public static Int32 GetAge(this DateTime dateOfBirth)
{
    var today = DateTime.Today;

    var a = (today.Year * 100 + today.Month) * 100 + today.Day;
    var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;

    return (a - b) / 10000;
}
Kols
  • 3,641
  • 2
  • 34
  • 42
ScArcher2
  • 85,501
  • 44
  • 121
  • 160
  • 13
    Actually this is great for usage on MS-SQL with datetime-fields (total days since 01-011900) – Patrik Jul 03 '15 at 12:01
  • 1
    in your alternate answer, you can avoid integer overflow by subtracting the years then subtract month * 30.5 + day and divide by 366 – numerek Sep 03 '15 at 20:14
  • 9
    @numerek Please post your suggested modifications as their own answer. For what it's worth, the current year times 10000 is nowhere near an integer overflow, by two orders of magnitude. 20,150,000 vs 2,147,483,648 – GalacticCowboy Sep 03 '15 at 20:23
  • 1
    It would be better to add a parameter: float.Parse(x, CultureInfo.InvariantCulture) because some locals use comma instead of dot for a delimiter in fractional numbers – Vlad Krylov Mar 28 '16 at 08:39
  • 1
    DateTime.MaxValue year is 9999, MinValue year is 1, overflow is not possible. – Antonín Lejsek Jan 01 '17 at 02:07
  • 2
    This answer assumes that leap day babies have their birthdays on 1st March on non-leap years. – Jamie Kitson Feb 13 '18 at 09:38
  • 1
    asking for question for very old post `int age = (now - dob) / 10000;` why you subtracts by 10000 ? – Monojit Sarkar Feb 25 '18 at 08:24
  • 12
    @LongChalk `20180101 - 20171231 = 8870`. Drop the last 4 digits and you have (an implied) `0` for the age. How did you get `1`? – Rufus L Jun 14 '18 at 20:36
  • 2
    @RufusL Its `0`, not `1`. `floor(8870 / 10000) == 0`. You are "counting" ten thousands, and at `8870` you have zero ten thousands. – flindeberg Jul 03 '18 at 18:13
  • 1
    Jumping on the bandwagon pretty late but you could also include a `TimeOfDay` difference check to get the age up to the tick, at least in C#. – JansthcirlU Nov 26 '20 at 17:31
422

Here is a test snippet:

DateTime bDay = new DateTime(2000, 2, 29);
DateTime now = new DateTime(2009, 2, 28);
MessageBox.Show(string.Format("Test {0} {1} {2}",
                CalculateAgeWrong1(bDay, now),      // outputs 9
                CalculateAgeWrong2(bDay, now),      // outputs 9
                CalculateAgeCorrect(bDay, now),     // outputs 8
                CalculateAgeCorrect2(bDay, now)));  // outputs 8

Here you have the methods:

public int CalculateAgeWrong1(DateTime birthDate, DateTime now)
{
    return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;
}

public int CalculateAgeWrong2(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;

    if (now < birthDate.AddYears(age))
        age--;

    return age;
}

public int CalculateAgeCorrect(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;

    if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))
        age--;

    return age;
}

public int CalculateAgeCorrect2(DateTime birthDate, DateTime now)
{
    int age = now.Year - birthDate.Year;

    // For leap years we need this
    if (birthDate > now.AddYears(-age)) 
        age--;
    // Don't use:
    // if (birthDate.AddYears(age) > now) 
    //     age--;

    return age;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
RMA
  • 231
  • 1
  • 3
  • 2
  • 40
    While this code works, it asserts that a person born on a leap day attains the next year of age on March 1st on non-leap years, rather than on February 28th. In reality, *either option may be correct*. [Wikipedia has something to say about this](http://en.wikipedia.org/wiki/Leap_day#Births). So while your code is not "wrong", neither is the accepted solution. – Matt Johnson-Pint Aug 17 '14 at 05:44
  • 29
    @MattJohnson I think that's actually correct. If my bday was Feb 29, then Feb 28 my bday hasn't passed, and I should still be the same age as on Feb 27. On March 1, however, we have passed my bday and I should be the next age. In the US, a business that sells alcohol will have a sign that says something like "If you were born after this day in YYYY, you can't purchase alcohol" (where YYYY changes every year). That means that someone born on Feb 29 cannot buy alcohol on Feb 28 in the year they turn 21 (most places), and lends support to the idea that they are not a year older until March 1. – jfren484 Jul 12 '16 at 17:18
  • 7
    @jfren484 - read the Wikipedia article. It varies considerably across jurisdictions. – Matt Johnson-Pint Jul 12 '16 at 19:26
  • 13
    @jfren484 Your claim has absolutely nothing to do with philosophy; but everything to do with ***your own personal feeling***. When a person born on 29 Feb "ages" is largely unimportant unless the age forms a 'legal age boundary' (e.g. Can buy alcohol, vote, get pension, join army, get driving license). Consider US drinking age (21 years): For most people that's 7670 days. It's 7671 days if born before 29 Feb in leap year or from 1 Mar before leap year. If born on 29 Feb: 28 Feb is 7670 days and 1 Mar is 7671 days. ***The choice is arbitrary*** it can go either way. – Disillusioned Mar 04 '17 at 10:06
  • 9
    @CraigYoung You don't understand what I meant by philosophically. I used that term as a contrast to legally. If one is writing an application that needs to know the legal age of a person, then all they need to know is how the legal jurisdictions that their application is used in/for treat people born on Feb 29. If, however, we're talking about how that *should* be treated, then that is by definition, philosophy. And yes, the opinion I gave is my own opinion, but as I said, I think it would be easier to argue for March 1 than it would be for Feb 28. – jfren484 Mar 04 '17 at 18:45
  • The link @MattJohnson-Pint brought in comment above from 2014, no longer leads to this information. What he saw, was apparently this: [Wikipedia historical version](https://en.wikipedia.org/w/index.php?title=February_29&oldid=620734326#Births) – Jeppe Stig Nielsen Sep 09 '22 at 08:38
  • @JeppeStigNielsen - Thanks. It looks like it has migrated to https://en.wikipedia.org/wiki/Leap_year#Birthdays – Matt Johnson-Pint Sep 09 '22 at 16:47
125

The simple answer to this is to apply AddYears 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.

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.

Further, an Age method lends itself to be added as an extension to DateTime. By this you can obtain the age in the simplest possible way:

  1. List item

int age = birthDate.Age();

public static class DateTimeExtensions
{
    /// <summary>
    /// Calculates the age in years of the current System.DateTime object today.
    /// </summary>
    /// <param name="birthDate">The date of birth</param>
    /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>
    public static int Age(this DateTime birthDate)
    {
        return Age(birthDate, DateTime.Today);
    }

    /// <summary>
    /// Calculates the age in years of the current System.DateTime object on a later date.
    /// </summary>
    /// <param name="birthDate">The date of birth</param>
    /// <param name="laterDate">The date on which to calculate the age.</param>
    /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>
    public static int Age(this DateTime birthDate, DateTime laterDate)
    {
        int age;
        age = laterDate.Year - birthDate.Year;

        if (age > 0)
        {
            age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));
        }
        else
        {
            age = 0;
        }

        return age;
    }
}

Now, run this test:

class Program
{
    static void Main(string[] args)
    {
        RunTest();
    }

    private static void RunTest()
    {
        DateTime birthDate = new DateTime(2000, 2, 28);
        DateTime laterDate = new DateTime(2011, 2, 27);
        string iso = "yyyy-MM-dd";

        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                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());
            }
        }

        Console.ReadKey();
    }
}

The critical date example is this:

Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11

Output:

{
    Birth date: 2000-02-28  Later date: 2011-02-27  Age: 10
    Birth date: 2000-02-28  Later date: 2011-02-28  Age: 11
    Birth date: 2000-02-28  Later date: 2011-03-01  Age: 11
    Birth date: 2000-02-29  Later date: 2011-02-27  Age: 10
    Birth date: 2000-02-29  Later date: 2011-02-28  Age: 11
    Birth date: 2000-02-29  Later date: 2011-03-01  Age: 11
    Birth date: 2000-03-01  Later date: 2011-02-27  Age: 10
    Birth date: 2000-03-01  Later date: 2011-02-28  Age: 10
    Birth date: 2000-03-01  Later date: 2011-03-01  Age: 11
}

And for the later date 2012-02-28:

{
    Birth date: 2000-02-28  Later date: 2012-02-28  Age: 12
    Birth date: 2000-02-28  Later date: 2012-02-29  Age: 12
    Birth date: 2000-02-28  Later date: 2012-03-01  Age: 12
    Birth date: 2000-02-29  Later date: 2012-02-28  Age: 11
    Birth date: 2000-02-29  Later date: 2012-02-29  Age: 12
    Birth date: 2000-02-29  Later date: 2012-03-01  Age: 12
    Birth date: 2000-03-01  Later date: 2012-02-28  Age: 11
    Birth date: 2000-03-01  Later date: 2012-02-29  Age: 11
    Birth date: 2000-03-01  Later date: 2012-03-01  Age: 12
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
camelCasus
  • 61
  • 1
  • 2
  • 3
  • 6
    A comment regarding having the 29th Feb birthday on 1st March, technically, having it on the 28th is too early (1 day early in fact). On the 1st is one day too late. But since the birthday is between, using the 1st to calculate the age in non-leap years makes more sense to me, since that person is indeed that old on March 1st (and 2nd and 3rd) every year, but not on Feb 28th. – CyberClaw Jul 24 '18 at 16:31
  • 3
    From a software design point, writing this as an extension method doesn't make much sense to me. `date.Age(other)`? – marsze Dec 12 '18 at 08:11
  • 2
    @marsze, I think it does make a lot of sense if you have your variables named accordingly. ```dob.Age(toDay)``` – A.G. Sep 24 '21 at 17:13
99

My suggestion

int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);

That seems to have the year changing on the right date. (I spot tested up to age 107.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James Curran
  • 101,701
  • 37
  • 181
  • 258
  • 31
    I don't think Harry Patch would have appreciated your spot-testing methodology: http://www.latimes.com/news/obituaries/la-me-harry-patch26-2009jul26,0,7608030.story – MusiGenesis Aug 01 '09 at 16:03
  • 4
    Google says `days in a year = 365.242199` – mpen Aug 12 '10 at 05:28
  • 13
    The average length of a year in the Gregorian Calendar is 365.2425 days. – dan04 Oct 06 '10 at 02:01
  • 7
    I would say, this is one of the simplest solutions and it's *good enough*. Who cares if I am half a day before my Xth birthday and the program says I am X years old. The program is more or less right, although not mathematically. I really like this solution. – Peter Perháč Mar 09 '11 at 12:07
  • 20
    ^^ Because sometimes it's important. In my testing this fails on the persons birthday, it reports them younger than they are. – ChadT Mar 25 '11 at 05:27
  • 3
    this is what I would start with, too, but testing it, it often gets a person's birthday wrong. – Dave Cousineau Jan 01 '16 at 20:51
  • 1
    @ChadT what solution have you come up with so this works? users constantly complain about Birthday not working on their birthdays and watch clock rundown. – Mahdi Yusuf Nov 07 '16 at 17:55
  • 1
    Not going to bother to test it but it would seem that if you're only problem with this is that you want the result to increment a day sooner, you should probably be able to get away with: `int age = (int) (((DateTime.Now - bday).TotalDays+1)/365.242199);` – krowe2 Nov 21 '18 at 15:44
  • 2
    It should be spot tested for four consecutive years as the error is accumulative (reset back by one day every four years by the leap day - like today!). – Peter Mortensen Feb 29 '20 at 01:26
94

Another function, not by me but found on the web and refined it a bit:

public static int GetAge(DateTime birthDate)
{
    DateTime n = DateTime.Now; // To avoid a race condition around midnight
    int age = n.Year - birthDate.Year;

    if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))
        age--;

    return age;
}

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 :-)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Stum
  • 177,530
  • 117
  • 400
  • 535
62

2 Main problems to solve are:

1. Calculate Exact age - in years, months, days, etc.

2. Calculate Generally perceived age - people usually do not care how old they exactly are, they just care when their birthday in the current year is.


Solution for 1 is obvious:

DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today;     //we usually don't care about birth time
TimeSpan age = today - birth;        //.NET FCL should guarantee this as precise
double ageInDays = age.TotalDays;    //total number of days ... also precise
double daysInYear = 365.2425;        //statistical value for 400 years
double ageInYears = ageInDays / daysInYear;  //can be shifted ... not so precise

Solution for 2 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":

DateTime birth = DateTime.Parse("1.1.2000");
DateTime today = DateTime.Today;
int age = today.Year - birth.Year;    //people perceive their age in years

if (today.Month < birth.Month ||
   ((today.Month == birth.Month) && (today.Day < birth.Day)))
{
  age--;  //birthday in current year not yet reached, we are 1 year younger ;)
          //+ no birthday for 29.2. guys ... sorry, just wrong date for birth
}

Notes to 2.:

  • This is my preferred solution
  • We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years
  • I have put there little more lines for readability

Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness:

public static int GetAge(DateTime bithDay, DateTime today) 
{ 
  //chosen solution method body
}

public static int GetAge(DateTime birthDay) 
{ 
  return GetAge(birthDay, DateTime.Now);
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Marcel Toth
  • 10,716
  • 4
  • 22
  • 17
56

The best way that I know of because of leap years and everything is:

DateTime birthDate = new DateTime(2000,3,1);
int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nick Berardi
  • 54,393
  • 15
  • 113
  • 135
  • 2
    Buggy, just because it doesn't handle leap years/days. If you run it on your birthday, it'll calculate the wrong age half of the time. – lidqy Sep 05 '21 at 12:42
53

Here's a one-liner:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SillyMonkey
  • 1,334
  • 3
  • 11
  • 14
  • 27
    This is broken. Made testable: public static int CalculateAge(DateTime dateOfBirth, DateTime dateToCalculateAge) { return new DateTime(dateToCalculateAge.Subtract(dateOfBirth).Ticks).Year - 1; } ...Gives age 14 when I input 1990-06-01 and calculate the age on the day BEFORE his 14th birthday (1990-05-31). – Kjensen Feb 05 '11 at 21:42
  • 1
    @Kjensen The one-day shift is caused by different counts of 29th FEBs in the real time range (dateOfBirth to dateToCalculateAge) and the time range created by DateTime.Substract, which always implicitly compares to DateTime.Min, i.e. the 1-JAN-0001. From 31st may 1990 to 1st JUN 2005 you have four such leap days, From 1st JAN 0001 to 1st JAN 0015 you only have three 29th FEBs. – lidqy Sep 05 '21 at 11:14
46

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.

public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)
{
    return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);
}

You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear.

Obviously this is done as an extension method on DateTime, 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 DateTime.Now, just for completeness.

Kols
  • 3,641
  • 2
  • 34
  • 42
David Wengier
  • 10,061
  • 5
  • 39
  • 43
  • 11
    I think this can be off by one day when exactly one of dateOfBirth or dateAsAt falls in a leap year. Consider the age of a person born on March 1, 2003 on February 29, 2004. To rectify this, you need to do a lexicographic comparison of (Month, DayOfMonth) pairs and use that for the conditional. – Doug McClean Dec 23 '08 at 15:36
  • 4
    it's also not going to show the right age as of your birthday. – dotjoe Jan 29 '09 at 21:19
38

This gives "more detail" to this question. Maybe this is what you're looking for

DateTime birth = new DateTime(1974, 8, 29);
DateTime today = DateTime.Now;
TimeSpan span = today - birth;
DateTime age = DateTime.MinValue + span;

// Make adjustment due to MinValue equalling 1/1/1
int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;

// Print out not only how many years old they are but give months and days as well
Console.Write("{0} years, {1} months, {2} days", years, months, days);
g t
  • 7,287
  • 7
  • 50
  • 85
  • 1
    This does not work all the time. Adding a Span to the DateTime.MinValue could work boes this does not account for leap years etc. If you add the Years, months and days to Age using the AddYears(), AddMonths and AddDays() function it will not always return the Datetime.Now date. – Athanasios Kataras Oct 23 '13 at 09:44
  • 3
    timespan itself automatically takes into account leap years between 2 dates so I'm not sure what your getting on about. I have asked on microsoft forums and microsoft has confirmed it takes into account leap years between 2 dates. – Jacqueline Loriault Oct 23 '13 at 19:29
  • 3
    Consider the following TWO senarios. 1st DateTime.Now is 1/1/2001 and a child is born on 1/1/2000. 2000 is a leap year and the result will be 1years, 0 months and 1 days. In the second senarion DateTime.Now is 1/1/2002 and the child is born on 1/1/2001. In this case the result will be 1 years, 0 months and 0 days. That will happen because you are adding the timespan on a non-leap year. If DateTime.MinValue was a leap year then the results would be 1 year at the first and 0 years 11 months and 30 days. (Try it in your code). – Athanasios Kataras Oct 24 '13 at 10:31
  • 1
    Upvote! I came up with a solution that is pretty much identical (I used DateTime.MinValue.AddTicks(span.Ticks) instead of +, but the result is the same and yours has a few characters less code). – Makotosan Mar 17 '15 at 20:57
  • 1
    @AthanasiosKataras, I don't understand your comment "If DateTime.MinValue was a leap year...". When will DateTime.MinValue be a leap year? It will always be "1/1/0001", which is not a leap year. – Makotosan Mar 17 '15 at 21:00
  • 5
    You are quite right it's not. But IF it was that would be the result. Why does it matter? It doesn't. In either case leap or not then there are examples where this does not work. That was what I wanted to show. The DIFF is correct. Span takes into account leap years. But ADDING to a base date is not. Try the examples in code and you will see I'm right. – Athanasios Kataras Mar 18 '15 at 18:20
37

I use this:

public static class DateTimeExtensions
{
    public static int Age(this DateTime birthDate)
    {
        return Age(birthDate, DateTime.Now);
    }

    public static int Age(this DateTime birthDate, DateTime offsetDate)
    {
        int result=0;
        result = offsetDate.Year - birthDate.Year;

        if (offsetDate.DayOfYear < birthDate.DayOfYear)
        {
              result--;
        }

        return result;
    }
}
Noam M
  • 3,156
  • 5
  • 26
  • 41
Elmer
  • 9,147
  • 2
  • 48
  • 38
32

Here's yet another answer:

public static int AgeInYears(DateTime birthday, DateTime today)
{
    return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}

This has been extensively unit-tested. It does look a bit "magic". The number 372 is the number of days there would be in a year if every month had 31 days.

The explanation of why it works (lifted from here) is:

Let's set Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day

age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372

We know that what we need is either Yn-Yb if the date has already been reached, Yn-Yb-1 if it has not.

a) If Mn<Mb, we have -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30

-371 <= 31*(Mn - Mb) + (Dn - Db) <= -1

With integer division

(31*(Mn - Mb) + (Dn - Db)) / 372 = -1

b) If Mn=Mb and Dn<Db, we have 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1

With integer division, again

(31*(Mn - Mb) + (Dn - Db)) / 372 = -1

c) If Mn>Mb, we have 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30

1 <= 31*(Mn - Mb) + (Dn - Db) <= 371

With integer division

(31*(Mn - Mb) + (Dn - Db)) / 372 = 0

d) If Mn=Mb and Dn>Db, we have 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 30

With integer division, again

(31*(Mn - Mb) + (Dn - Db)) / 372 = 0

e) If Mn=Mb and Dn=Db, we have 31*(Mn - Mb) + Dn-Db = 0

and therefore (31*(Mn - Mb) + (Dn - Db)) / 372 = 0

Community
  • 1
  • 1
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
30

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:

using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlInt32 CalculateAge(string strBirthDate)
    {
        DateTime dtBirthDate = new DateTime();
        dtBirthDate = Convert.ToDateTime(strBirthDate);
        DateTime dtToday = DateTime.Now;

        // get the difference in years
        int years = dtToday.Year - dtBirthDate.Year;

        // subtract another year if we're before the
        // birth day in the current year
        if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))
            years=years-1;

        int intCustomerAge = years;
        return intCustomerAge;
    }
};
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
user2601
  • 228
  • 1
  • 5
  • 7
26

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:

public void LoopAge(DateTime myDOB, DateTime FutureDate)
{
    int years = 0;
    int months = 0;
    int days = 0;

    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);

    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);

    while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
    {
        months++;

        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (FutureDate.Day >= myDOB.Day)
    {
        days = days + FutureDate.Day - myDOB.Day;
    }
    else
    {
        months--;

        if (months < 0)
        {
            years--;
            months = months + 12;
        }

        days +=
            DateTime.DaysInMonth(
                FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month
            ) + FutureDate.Day - myDOB.Day;

    }

    //add an extra day if the dob is a leap day
    if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
    {
        //but only if the future date is less than 1st March
        if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))
            days++;
    }

}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
21

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.

Below is my implementation, it is not as simple as what I imagined, especially to deal with date like 2/28.

public static string HowOld(DateTime birthday, DateTime now)
{
    if (now < birthday)
        throw new ArgumentOutOfRangeException("birthday must be less than now.");

    TimeSpan diff = now - birthday;
    int diffDays = (int)diff.TotalDays;

    if (diffDays > 7)//year, month and week
    {
        int age = now.Year - birthday.Year;

        if (birthday > now.AddYears(-age))
            age--;

        if (age > 0)
        {
            return age + (age > 1 ? " years" : " year");
        }
        else
        {// month and week
            DateTime d = birthday;
            int diffMonth = 1;

            while (d.AddMonths(diffMonth) <= now)
            {
                diffMonth++;
            }

            age = diffMonth-1;

            if (age == 1 && d.Day > now.Day)
                age--;

            if (age > 0)
            {
                return age + (age > 1 ? " months" : " month");
            }
            else
            {
                age = diffDays / 7;
                return age + (age > 1 ? " weeks" : " week");
            }
        }
    }
    else if (diffDays > 0)
    {
        int age = diffDays;
        return age + (age > 1 ? " days" : " day");
    }
    else
    {
        int age = diffDays;
        return "just born";
    }
}

This implementation has passed below test cases.

[TestMethod]
public void TestAge()
{
    string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("11 years", age);

    age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("10 months", age);

    age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("11 months", age);

    age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("11 months", age);

    age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));
    Assert.AreEqual("1 year", age);

    age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));
    Assert.AreEqual("1 month", age);

    // NOTE.
    // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);
    // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);
    age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));
    Assert.AreEqual("4 weeks", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));
    Assert.AreEqual("3 weeks", age);

    age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));
    Assert.AreEqual("1 month", age);

    age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));
    Assert.AreEqual("3 weeks", age);

    age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));
    Assert.AreEqual("4 weeks", age);

    age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 week", age);

    age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));
    Assert.AreEqual("5 days", age);

    age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));
    Assert.AreEqual("1 day", age);

    age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));
    Assert.AreEqual("just born", age);

    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));
    Assert.AreEqual("8 years", age);

    age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));
    Assert.AreEqual("9 years", age);

    Exception e = null;

    try
    {
        age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));
    }
    catch (ArgumentOutOfRangeException ex)
    {
        e = ex;
    }

    Assert.IsTrue(e != null);
}

Hope it's helpful.

Markus Safar
  • 6,324
  • 5
  • 28
  • 44
rockXrock
  • 3,403
  • 1
  • 25
  • 18
21

Keeping it simple (and possibly stupid:)).

DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);
TimeSpan ts = DateTime.Now - birth;
Console.WriteLine("You are approximately " + ts.TotalSeconds.ToString() + " seconds old.");
Kols
  • 3,641
  • 2
  • 34
  • 42
  • 1
    TimeSpan was my first choice, but found that it doesn't offer a TotalYears property. You could try (ts.TotalDays / 365) - but it doesn't account for leap years etc. – Lazlow Sep 21 '11 at 20:14
21

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.

public int AgeInYears(DateTime birthDate, DateTime referenceDate)
{
  Debug.Assert(referenceDate >= birthDate, 
               "birth date must be on or prior to the reference date");

  DateTime birth = birthDate.Date;
  DateTime reference = referenceDate.Date;
  int years = (reference.Year - birth.Year);

  //
  // an offset of -1 is applied if the birth date has 
  // not yet occurred in the current year.
  //
  if (reference.Month > birth.Month);
  else if (reference.Month < birth.Month) 
    --years;
  else // in birth month
  {
    if (reference.Day < birth.Day)
      --years;
  }

  return years ;
}

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, per Wikipedia, if you're born on February 29th in various jurisdictions, you're non-leap year birthday varies:

  • In the United Kingdom and Hong Kong: it's the ordinal day of the year, so the next day, March 1st is your birthday.
  • In New Zealand: it's the previous day, February 28th for the purposes of driver licencing, and March 1st for other purposes.
  • Taiwan: it's February 28th.

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.

To that end, an improvement:

public enum LeapDayRule
{
  OrdinalDay     = 1 ,
  LastDayOfMonth = 2 ,
}

static int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)
{
  bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);
  DateTime cutoff;

  if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))
  {
    switch (ruleInEffect)
    {
      case LeapDayRule.OrdinalDay:
        cutoff = new DateTime(reference.Year, 1, 1)
                             .AddDays(birth.DayOfYear - 1);
        break;

      case LeapDayRule.LastDayOfMonth:
        cutoff = new DateTime(reference.Year, birth.Month, 1)
                             .AddMonths(1)
                             .AddDays(-1);
        break;

      default:
        throw new InvalidOperationException();
    }
  }
  else
  {
    cutoff = new DateTime(reference.Year, birth.Month, birth.Day);
  }

  int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);
  return age < 0 ? 0 : age;
}

It should be noted that this code assumes:

  • A western (European) reckoning of age, and
  • A calendar, like the Gregorian calendar that inserts a single leap day at the end of a month.
Kols
  • 3,641
  • 2
  • 34
  • 42
Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
20

This is not a direct answer, but more of a philosophical reasoning about the problem at hand from a quasi-scientific point of view.

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 second, ergo the correct generic answer should be (of course assuming normalized DateTime and taking no regard whatsoever to relativistic effects):

var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;

In the Christian way of calculating age in years:

var then = ... // Then, in this case the birthday
var now = DateTime.UtcNow;
int age = now.Year - then.Year;
if (now.AddYears(-age) < then) age--;

In finance there is a similar problem when calculating something often referred to as the Day Count Fraction, which roughly is a number of years for a given period. And the age issue is really a time measuring issue.

Example for the actual/actual (counting all days "correctly") convention:

DateTime start, end = .... // Whatever, assume start is before end

double startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);
double endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);
double middleContribution = (double) (end.Year - start.Year - 1);

double DCF = startYearContribution + endYearContribution + middleContribution;

Another quite common way to measure time generally is by "serializing" (the dude who named this date convention must seriously have been trippin'):

DateTime start, end = .... // Whatever, assume start is before end
int days = (end - start).Days;

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 :)

Dixit
  • 1,359
  • 3
  • 18
  • 39
flindeberg
  • 4,887
  • 1
  • 24
  • 37
19
TimeSpan diff = DateTime.Now - birthdayDateTime;
string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff);

I'm not sure how exactly you'd like it returned to you, so I just made a readable string.

Kols
  • 3,641
  • 2
  • 34
  • 42
Dakotah Hicock
  • 380
  • 2
  • 15
17

Here is a solution.

DateTime dateOfBirth = new DateTime(2000, 4, 18);
DateTime currentDate = DateTime.Now;

int ageInYears = 0;
int ageInMonths = 0;
int ageInDays = 0;

ageInDays = currentDate.Day - dateOfBirth.Day;
ageInMonths = currentDate.Month - dateOfBirth.Month;
ageInYears = currentDate.Year - dateOfBirth.Year;

if (ageInDays < 0)
{
    ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);
    ageInMonths = ageInMonths--;

    if (ageInMonths < 0)
    {
        ageInMonths += 12;
        ageInYears--;
    }
}

if (ageInMonths < 0)
{
    ageInMonths += 12;
    ageInYears--;
}

Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);
Dez
  • 5,702
  • 8
  • 42
  • 51
Rajeshwaran S P
  • 582
  • 1
  • 7
  • 15
16

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.

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;

    if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;

    return age;
}




Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mjb
  • 7,649
  • 8
  • 44
  • 60
15

I have a customized method to calculate age, plus a bonus validation message just in case it helps:

public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)
{
    years = 0;
    months = 0;
    days = 0;

    DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);
    DateTime tmpnow = new DateTime(now.Year, now.Month, 1);

    while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)
    {
        months++;
        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (now.Day >= dob.Day)
        days = days + now.Day - dob.Day;
    else
    {
        months--;
        if (months < 0)
        {
            years--;
            months = months + 12;
        }
        days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;
    }

    if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))
        days++;

}   

private string ValidateDate(DateTime dob) //This method will validate the date
{
    int Years = 0; int Months = 0; int Days = 0;

    GetAge(dob, DateTime.Now, out Years, out Months, out Days);

    if (Years < 18)
        message =  Years + " is too young. Please try again on your 18th birthday.";
    else if (Years >= 65)
        message = Years + " is too old. Date of Birth must not be 65 or older.";
    else
        return null; //Denotes validation passed
}

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:

DateTime dob = DateTime.Parse("03/10/1982");  

string message = ValidateDate(dob);

lbldatemessage.Visible = !StringIsNullOrWhitespace(message);
lbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string

Remember you can format the message any way you like.

WonderWorker
  • 8,539
  • 4
  • 63
  • 74
DareDevil
  • 5,249
  • 6
  • 50
  • 88
14

How about this solution?

static string CalcAge(DateTime birthDay)
{
    DateTime currentDate = DateTime.Now;         
    int approximateAge = currentDate.Year - birthDay.Year;
    int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - 
        (currentDate.Month * 30 + currentDate.Day) ;

    if (approximateAge == 0 || approximateAge == 1)
    {                
        int month =  Math.Abs(daysToNextBirthDay / 30);
        int days = Math.Abs(daysToNextBirthDay % 30);

        if (month == 0)
            return "Your age is: " + daysToNextBirthDay + " days";

        return "Your age is: " + month + " months and " + days + " days"; ;
    }

    if (daysToNextBirthDay > 0)
        return "Your age is: " + --approximateAge + " Years";

    return "Your age is: " + approximateAge + " Years"; ;
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
Doron
  • 1
  • 1
  • 2
13

This classic question is deserving of a Noda Time solution.

static int GetAge(LocalDate dateOfBirth)
{
    Instant now = SystemClock.Instance.Now;

    // The target time zone is important.
    // It should align with the *current physical location* of the person
    // you are talking about.  When the whereabouts of that person are unknown,
    // then you use the time zone of the person who is *asking* for the age.
    // The time zone of birth is irrelevant!

    DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"];

    LocalDate today = now.InZone(zone).Date;

    Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);

    return (int) period.Years;
}

Usage:

LocalDate dateOfBirth = new LocalDate(1976, 8, 27);
int age = GetAge(dateOfBirth);

You might also be interested in the following improvements:

  • Passing in the clock as an IClock, instead of using SystemClock.Instance, would improve testability.

  • The target time zone will likely change, so you'd want a DateTimeZone parameter as well.

See also my blog post on this subject: Handling Birthdays, and Other Anniversaries

Kols
  • 3,641
  • 2
  • 34
  • 42
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
13
private int GetAge(int _year, int _month, int _day
{
    DateTime yourBirthDate= new DateTime(_year, _month, _day);

    DateTime todaysDateTime = DateTime.Today;
    int noOfYears = todaysDateTime.Year - yourBirthDate.Year;

    if (DateTime.Now.Month < yourBirthDate.Month ||
        (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))
    {
        noOfYears--;
    }

    return  noOfYears;
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
AEMLoviji
  • 3,217
  • 9
  • 37
  • 61
10

SQL version:

declare @dd smalldatetime = '1980-04-01'
declare @age int = YEAR(GETDATE())-YEAR(@dd)
if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1

print @age  
xenedia
  • 314
  • 2
  • 9
10

The following approach (extract from Time Period Library for .NET class DateDiff) considers the calendar of the culture info:

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2 )
{
  return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );
} // YearDiff

// ----------------------------------------------------------------------
private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )
{
  if ( date1.Equals( date2 ) )
  {
    return 0;
  }

  int year1 = calendar.GetYear( date1 );
  int month1 = calendar.GetMonth( date1 );
  int year2 = calendar.GetYear( date2 );
  int month2 = calendar.GetMonth( date2 );

  // find the the day to compare
  int compareDay = date2.Day;
  int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );
  if ( compareDay > compareDaysPerMonth )
  {
    compareDay = compareDaysPerMonth;
  }

  // build the compare date
  DateTime compareDate = new DateTime( year1, month2, compareDay,
    date2.Hour, date2.Minute, date2.Second, date2.Millisecond );
  if ( date2 > date1 )
  {
    if ( compareDate < date1 )
    {
      compareDate = compareDate.AddYears( 1 );
    }
  }
  else
  {
    if ( compareDate > date1 )
    {
      compareDate = compareDate.AddYears( -1 );
    }
  }
  return year2 - calendar.GetYear( compareDate );
} // YearDiff

Usage:

// ----------------------------------------------------------------------
public void CalculateAgeSamples()
{
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years
  PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );
  // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years
} // CalculateAgeSamples

// ----------------------------------------------------------------------
public void PrintAge( DateTime birthDate, DateTime moment )
{
  Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) );
} // PrintAge
Kols
  • 3,641
  • 2
  • 34
  • 42
9

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.

    public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)
    {
        //----------------------------------------------------------------------
        // Can't determine age if we don't have a dates.
        //----------------------------------------------------------------------
        if (ndtBirthDate == null) return null;
        if (ndtReferralDate == null) return null;

        DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);
        DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);

        //----------------------------------------------------------------------
        // Create our Variables
        //----------------------------------------------------------------------
        Dictionary<string, int> dYMD = new Dictionary<string,int>();
        int iNowDate, iBirthDate, iYears, iMonths, iDays;
        string sDif = "";

        //----------------------------------------------------------------------
        // Store off current date/time and DOB into local variables
        //---------------------------------------------------------------------- 
        iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd"));
        iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd"));

        //----------------------------------------------------------------------
        // Calculate Years
        //----------------------------------------------------------------------
        sDif = (iNowDate - iBirthDate).ToString();
        iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));

        //----------------------------------------------------------------------
        // Store Years in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Years", iYears);

        //----------------------------------------------------------------------
        // Calculate Months
        //----------------------------------------------------------------------
        if (dtBirthDate.Month > dtReferralDate.Month)
            iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;
        else
            iMonths = dtBirthDate.Month - dtReferralDate.Month;

        //----------------------------------------------------------------------
        // Store Months in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Months", iMonths);

        //----------------------------------------------------------------------
        // Calculate Remaining Days
        //----------------------------------------------------------------------
        if (dtBirthDate.Day > dtReferralDate.Day)
            //Logic: Figure out the days in month previous to the current month, or the admitted month.
            //       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.
            //       then take the referral date and simply add the number of days the person has lived this month.

            //If referral date is january, we need to go back to the following year's December to get the days in that month.
            if (dtReferralDate.Month == 1)
                iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day;       
            else
                iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day;       
        else
            iDays = dtReferralDate.Day - dtBirthDate.Day;             

        //----------------------------------------------------------------------
        // Store Days in Return Value
        //----------------------------------------------------------------------
        dYMD.Add("Days", iDays);

        return dYMD;
}
Paul Fleming
  • 24,238
  • 8
  • 76
  • 113
Dylan Hayes
  • 2,331
  • 1
  • 23
  • 33
9

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).

DateTime now = DateTime.Today;
DateTime birthday = new DateTime(1991, 02, 03);//3rd feb

int age = now.Year - birthday.Year;

if (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet
  age--;

return age;
letsintegreat
  • 3,328
  • 4
  • 18
  • 39
musefan
  • 47,875
  • 21
  • 135
  • 185
8

I've made one small change to Mark Soen's answer: I've rewriten the third line so that the expression can be parsed a bit more easily.

public int AgeInYears(DateTime bday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - bday.Year;            
    if (bday.AddYears(age) > now) 
        age--;
    return age;
}

I've also made it into a function for the sake of clarity.

Dez
  • 5,702
  • 8
  • 42
  • 51
cdiggins
  • 17,602
  • 7
  • 105
  • 102
7

=== Common Saying (from months to years old) ===

If you just for common use, here is the code as your information:

DateTime today = DateTime.Today;
DateTime bday = DateTime.Parse("2016-2-14");
int age = today.Year - bday.Year;
var unit = "";

if (bday > today.AddYears(-age))
{
    age--;
}
if (age == 0)   // Under one year old
{
    age = today.Month - bday.Month;

    age = age <= 0 ? (12 + age) : age;  // The next year before birthday

    age = today.Day - bday.Day >= 0 ? age : --age;  // Before the birthday.day

    unit = "month";
}
else {
    unit = "year";
}

if (age > 1)
{
    unit = unit + "s";
}

The test result as below:

The birthday: 2016-2-14

2016-2-15 =>  age=0, unit=month;
2016-5-13 =>  age=2, unit=months;
2016-5-14 =>  age=3, unit=months; 
2016-6-13 =>  age=3, unit=months; 
2016-6-15 =>  age=4, unit=months; 
2017-1-13 =>  age=10, unit=months; 
2017-1-14 =>  age=11, unit=months; 
2017-2-13 =>  age=11, unit=months; 
2017-2-14 =>  age=1, unit=year; 
2017-2-15 =>  age=1, unit=year; 
2017-3-13 =>  age=1, unit=year;
2018-1-13 =>  age=1, unit=year; 
2018-1-14 =>  age=1, unit=year; 
2018-2-13 =>  age=1, unit=year; 
2018-2-14 =>  age=2, unit=years; 
John Jang
  • 2,567
  • 24
  • 28
7
private int GetYearDiff(DateTime start, DateTime end)
{
    int diff = end.Year - start.Year;
    if (end.DayOfYear < start.DayOfYear) { diff -= 1; }
    return diff;
}
[Fact]
public void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()
{
    //arrange
    var now = DateTime.Now;
    //act
    //assert
    Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed
    Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed
    Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed
}
Kols
  • 3,641
  • 2
  • 34
  • 42
K1laba
  • 154
  • 2
  • 5
6

Wow, I had to give my answer here... There are so many answers for such a simple question.

private int CalcularIdade(DateTime dtNascimento)
    {
        var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd"));
        var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd"));

        double diff = (nHoje - nAniversario) / 10000;

        var ret = Convert.ToInt32(Math.Truncate(diff));

        return ret;
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
5

It can be this simple:

int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lukas
  • 2,885
  • 2
  • 29
  • 31
5

This is the easiest way to answer this in a single line.

DateTime Dob = DateTime.Parse("1985-04-24");
 
int Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1;

This also works for leap years.

B2K
  • 2,541
  • 1
  • 22
  • 34
CathalMF
  • 9,705
  • 6
  • 70
  • 106
4

This may work:

public override bool IsValid(DateTime value)
{
    _dateOfBirth =  value;
    var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);
    if (yearsOld > 18)
        return true;
    return false;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
azamsharp
  • 19,710
  • 36
  • 144
  • 222
  • 6
    Wow. Why is value an object rather than a DateTime? The method signature should be `public override bool Is18OrOlder(DateTime birthday)` What about people who were born on February 29? Who said that we were trying to check whether or not the user was at least 18 years old? The question was "how do I calculate someone's age?" – Chris Shouts May 04 '10 at 20:57
  • 1
    How did that happen? I don't even remember putting IsValid as object. It should be DateTime! – azamsharp May 05 '10 at 00:03
  • 2
    Instead of the `if` statement, why not use `return yearsOld > 18;` – T_Bacon Mar 28 '18 at 08:41
4

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.

public string LoopAge(DateTime myDOB, DateTime FutureDate)
{
    int years = 0;
    int months = 0;
    int days = 0;

    DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);

    DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);

    while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
    {
        months++;
        if (months > 12)
        {
            years++;
            months = months - 12;
        }
    }

    if (FutureDate.Day >= myDOB.Day)
    {
        days = days + FutureDate.Day - myDOB.Day;
    }
    else
    {
        months--;
        if (months < 0)
        {
            years--;
            months = months + 12;
        }
        days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;

    }

    //add an extra day if the dob is a leap day
    if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)
    {
        //but only if the future date is less than 1st March
        if(FutureDate >= new DateTime(FutureDate.Year, 3,1))
            days++;
    }

    return "Years: " + years + " Months: " + months + " Days: " + days;
}
Jon
  • 610
  • 2
  • 6
  • 13
  • 1
    I like this solution the best, however, when calculating the months, it needs to be if(months >= 12). Try 6-8-2012 - 6-4-1993 to test. – Jerry Jun 08 '12 at 19:43
4
public string GetAge(this DateTime birthdate, string ageStrinFormat = null)
{
    var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);
    return string.Format(ageStrinFormat ?? "{0}/{1}/{2}",
        (date.Year - birthdate.Year), date.Month, date.Day);
}
Kols
  • 3,641
  • 2
  • 34
  • 42
BenSabry
  • 483
  • 4
  • 10
4

Here's a DateTime extender that adds the age calculation to the DateTime object.

public static class AgeExtender
{
    public static int GetAge(this DateTime dt)
    {
        int d = int.Parse(dt.ToString("yyyyMMdd"));
        int t = int.Parse(DateTime.Today.ToString("yyyyMMdd"));
        return (t-d)/10000;
    }
}
Kols
  • 3,641
  • 2
  • 34
  • 42
B2K
  • 2,541
  • 1
  • 22
  • 34
  • 4
    ugh, don't do this. ToString and int.Parse are both relatively expensive and while i'm anti micro-optimization hiding expensive functions in extension methods that should be trivial operations is not a good idea. – Yaur May 21 '11 at 07:31
  • 2
    Also, this is a duplicate of ScArcher2's answer: http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c/11942#11942 – David Schmitt May 30 '11 at 13:32
  • Yaur, I really like Elmer's solution that relies on DayOfYear, probably more efficient than mine. Note that my goal wasn't to change ScArcher2's algorithm, I felt that would be rude. It was simply to show how to implement an extension method. – B2K Sep 08 '11 at 22:23
3

Try this solution, it's working.

int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;
Kols
  • 3,641
  • 2
  • 34
  • 42
Narasimha
  • 3,802
  • 11
  • 55
  • 83
3

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:

DateTime myBD = new DateTime(1980, 10, 10);
TimeSpan difference = DateTime.Now.Subtract(myBD);

textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days";
Kols
  • 3,641
  • 2
  • 34
  • 42
3

Here is a function that is serving me well. No calculations , very simple.

    public static string ToAge(this DateTime dob, DateTime? toDate = null)
    {
        if (!toDate.HasValue)
            toDate = DateTime.Now;
        var now = toDate.Value;

        if (now.CompareTo(dob) < 0)
            return "Future date";

        int years = now.Year - dob.Year;
        int months = now.Month - dob.Month;
        int days = now.Day - dob.Day;

        if (days < 0)
        {
            months--;
            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;
        }

        if (months < 0)
        {
            years--;
            months = 12 + months;
        }


        return string.Format("{0} year(s), {1} month(s), {2} days(s)",
            years,
            months,
            days);
    }

And here is a unit test:

    [Test]
    public void ToAgeTests()
    {
        var date = new DateTime(2000, 1, 1);
        Assert.AreEqual("0 year(s), 0 month(s), 1 days(s)", new DateTime(1999, 12, 31).ToAge(date));
        Assert.AreEqual("0 year(s), 0 month(s), 0 days(s)", new DateTime(2000, 1, 1).ToAge(date));
        Assert.AreEqual("1 year(s), 0 month(s), 0 days(s)", new DateTime(1999, 1, 1).ToAge(date));
        Assert.AreEqual("0 year(s), 11 month(s), 0 days(s)", new DateTime(1999, 2, 1).ToAge(date));
        Assert.AreEqual("0 year(s), 10 month(s), 25 days(s)", new DateTime(1999, 2, 4).ToAge(date));
        Assert.AreEqual("0 year(s), 10 month(s), 1 days(s)", new DateTime(1999, 2, 28).ToAge(date));

        date = new DateTime(2000, 2, 15);
        Assert.AreEqual("0 year(s), 0 month(s), 28 days(s)", new DateTime(2000, 1, 18).ToAge(date));
    }
Tanjim Ahmed Khan
  • 650
  • 1
  • 9
  • 21
user1210708
  • 513
  • 4
  • 11
3

I have used the following for this issue. I know it's not very elegant, but it's working.

DateTime zeroTime = new DateTime(1, 1, 1);
var date1 = new DateTime(1983, 03, 04);
var date2 = DateTime.Now;
var dif = date2 - date1;
int years = (zeroTime + dif).Year - 1;
Log.DebugFormat("Years -->{0}", years);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VhsPiceros
  • 410
  • 1
  • 8
  • 17
3

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:

int AgeNow(DateTime birthday)
{
    return AgeAt(DateTime.Now, birthday);
}

int AgeAt(DateTime now, DateTime birthday)
{
    return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);
}

int AgeAt(DateTime now, DateTime birthday, Calendar calendar)
{
    // My age has increased on the morning of my
    // birthday even though I was born in the evening.
    now = now.Date;
    birthday = birthday.Date;

    var age = 0;
    if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.

    while (calendar.AddYears(birthday, age + 1) <= now)
    {
        age++;
    }
    return age;
}

Running this through in LINQPad gives this:

PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968
PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968
PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017

Code in LINQPad is here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sean Kearon
  • 10,987
  • 13
  • 77
  • 93
3

Just use:

(DateTime.Now - myDate).TotalHours / 8766.0

The current date - myDate = TimeSpan, get total hours and divide in the total hours per year and get exactly the age/months/days...

Kols
  • 3,641
  • 2
  • 34
  • 42
Moises Conejo
  • 157
  • 1
  • 5
3

I would strongly recommend using a NuGet package called AgeCalculator 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.

Palle Due
  • 5,929
  • 4
  • 17
  • 32
A.G.
  • 304
  • 2
  • 11
3

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:

Public Shared Function CalculateAge(BirthDate As DateTime) As Integer
    Dim HebCal As New System.Globalization.HebrewCalendar ()
    Dim now = DateTime.Now()
    Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)
    Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)
    If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1
    Return iAge
End Function
Kols
  • 3,641
  • 2
  • 34
  • 42
Moshe L
  • 1,797
  • 14
  • 19
2

Here is a very simple and easy to follow example.

private int CalculateAge()
{
//get birthdate
   DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
   int byear = dtBirth.Year;
   int bmonth = dtBirth.Month;
   int bday = dtBirth.Day;
   DateTime dtToday = DateTime.Now;
   int tYear = dtToday.Year;
   int tmonth = dtToday.Month;
   int tday = dtToday.Day;
   int age = tYear - byear;
   if (bmonth < tmonth)
       age--;
   else if (bmonth == tmonth && bday>tday)
   {
       age--;
   }
return age;
}
Stranger
  • 864
  • 4
  • 21
  • 48
2

With fewer conversions and UtcNow, this code can take care of someone born on the Feb 29 in a leap year:

public int GetAge(DateTime DateOfBirth)
{
    var Now = DateTime.UtcNow;
    return Now.Year - DateOfBirth.Year -
        (
            (
                Now.Month > DateOfBirth.Month ||
                (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)
            ) ? 0 : 1
        );
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vulcan raven
  • 32,612
  • 11
  • 57
  • 93
2

I've created an Age struct, which looks like this:

public struct Age : IEquatable<Age>, IComparable<Age>
{
    private readonly int _years;
    private readonly int _months;
    private readonly int _days;

    public int Years  { get { return _years; } }
    public int Months { get { return _months; } }
    public int Days { get { return _days; } }

    public Age( int years, int months, int days ) : this()
    {
        _years = years;
        _months = months;
        _days = days;
    }

    public static Age CalculateAge( DateTime dateOfBirth, DateTime date )
    {
        // Here is some logic that ressembles Mike's solution, although it
        // also takes into account months & days.
        // Ommitted for brevity.
        return new Age (years, months, days);
    }

    // Ommited Equality, Comparable, GetHashCode, functionality for brevity.
}
Matthew Crumley
  • 101,441
  • 24
  • 103
  • 129
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
2

Just because I don't think the top answer is that clear:

public static int GetAgeByLoop(DateTime birthday)
{
    var age = -1;

    for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))
    {
        age++;
    }

    return age;
}
Kols
  • 3,641
  • 2
  • 34
  • 42
dav_i
  • 27,509
  • 17
  • 104
  • 136
2

I would simply do this:

DateTime birthDay = new DateTime(1990, 05, 23);
DateTime age = DateTime.Now - birthDay;

This way you can calculate the exact age of a person, down to the millisecond if you want.

Kols
  • 3,641
  • 2
  • 34
  • 42
BrunoVT
  • 723
  • 6
  • 22
2

Simple Code

 var birthYear=1993;
 var age = DateTime.Now.AddYears(-birthYear).Year;
Kaval Patel
  • 670
  • 4
  • 20
Sunny Jangid
  • 578
  • 4
  • 19
2

Here is the simplest way to calculate someone's age.
Calculating 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.

 C#
        // get the difference in years
        int years = DateTime.Now.Year - BirthDate.Year; 
        // subtract another year if we're before the
        // birth day in the current year
        if (DateTime.Now.Month < BirthDate.Month || 
            (DateTime.Now.Month == BirthDate.Month && 
            DateTime.Now.Day < BirthDate.Day)) 
            years--;
  VB.NET
        ' get the difference in years
        Dim years As Integer = DateTime.Now.Year - BirthDate.Year
        ' subtract another year if we're before the
        ' birth day in the current year
        If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then 
            years = years - 1
        End If
wild coder
  • 880
  • 1
  • 12
  • 18
  • 5
    "Here is the simplest way to calculate someone's age." That's really not the simplest way. Using Noda Time, it's just `int years = Period.Between(birthDate, today).Years;`. – Jon Skeet Feb 08 '18 at 15:13
  • 2
    @JonSkeet To be fair, Noda Time is not part of any .Net standard. Given that, this *is* one of the simplest way to calculate the age of a person, in years. – Clearer Apr 23 '18 at 09:42
2
var birthDate = ... // DOB
var resultDate = DateTime.Now - birthDate;

Using resultDate you can apply TimeSpan properties whatever you want to display it.

Kols
  • 3,641
  • 2
  • 34
  • 42
1

How come the MSDN help did not tell you that? It looks so obvious:

System.DateTime birthTime = AskTheUser(myUser); // :-)
System.DateTime now = System.DateTime.Now;
System.TimeSpan age = now - birthTime; // As simple as that
double ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Archit
  • 630
  • 3
  • 10
  • 29
  • 11
    Well, that's fantastic, if you're in one of the zero countries on Earth where ages of adult human beings are measured in days. – Casey Oct 14 '14 at 20:47
1

Simple and readable with complementary method

public static int getAge(DateTime birthDate)
{
    var today = DateTime.Today;
    var age = today.Year - birthDate.Year;
    var monthDiff = today.Month - birthDate.Month;
    var dayDiff = today.Day - birthDate.Day;

    if (dayDiff < 0)
    {
        monthDiff--;
    }
    if (monthDiff < 0)
    {
       age--;
    }
    return age;
}
subcoder
  • 636
  • 8
  • 15
1
var EndDate = new DateTime(2022, 4, 21);
var StartDate = new DateTime(1986, 4, 25);
Int32 Months = EndDate.Month - StartDate.Month;
Int32 Years = EndDate.Year - StartDate.Year;
Int32 Days = EndDate.Day - StartDate.Day;

if (Days < 0)
{
    --Months;
}

if (Months < 0)
{
    --Years;
    Months += 12;
}
            
string Ages = Years.ToString() + " Year(s) " + Months.ToString() + " Month(s) ";
Anton Kesy
  • 119
  • 7
Md Shahriar
  • 2,072
  • 22
  • 11
1

Here's an answer making use of DateTimeOffset and manual math:

var diff = DateTimeOffset.Now - dateOfBirth;
var sinceEpoch = DateTimeOffset.UnixEpoch + diff;

return sinceEpoch.Year - 1970;
georgiosd
  • 3,038
  • 3
  • 39
  • 51
0

To calculate how many years old a person is,

DateTime dateOfBirth;

int ageInYears = DateTime.Now.Year - dateOfBirth.Year;

if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;
Kols
  • 3,641
  • 2
  • 34
  • 42
Kaval Patel
  • 670
  • 4
  • 20
0

Very simple answer

        DateTime dob = new DateTime(1991, 3, 4); 
        DateTime now = DateTime.Now; 
        int dobDay = dob.Day, dobMonth = dob.Month; 
        int add = -1; 
        if (dobMonth < now.Month)
        {
            add = 0;
        }
        else if (dobMonth == now.Month)
        {
            if(dobDay <= now.Day)
            {
                add = 0;
            }
            else
            {
                add = -1;
            }
        }
        else
        {
            add = -1;
        } 
        int age = now.Year - dob.Year + add;
Alexander
  • 46
  • 2
0
int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;
Console.WriteLine("Age {0}", Age);
Alexander Díaz
  • 471
  • 7
  • 12
0

I have no knowledge about DateTime but all I can do is this:

using System;
                    
public class Program
{
    public static int getAge(int month, int day, int year) {
        DateTime today = DateTime.Today;
        int currentDay = today.Day;
        int currentYear = today.Year;
        int currentMonth = today.Month;
        int age = 0;
        if (currentMonth < month) {
            age -= 1;
        } else if (currentMonth == month) {
            if (currentDay < day) {
                age -= 1;
            }
        }
        currentYear -= year;
        age += currentYear;
        return age;
    }
    public static void Main()
    {
        int ageInYears = getAge(8, 10, 2007);
        Console.WriteLine(ageInYears);
    }
}

A little confusing, but looking at the code more carefully, it will all make sense.

0
var startDate = new DateTime(2015, 04, 05);//your start date
var endDate = DateTime.Now;
var years = 0;
while(startDate < endDate) 
{
     startDate = startDate.AddYears(1);
     if(startDate < endDate) 
     {
         years++;
     }
}
Wylan Osorio
  • 1,136
  • 5
  • 19
  • 46
0

One could compute 'age' (i.e. the 'westerner' way) this way:

public static int AgeInYears(this System.DateTime source, System.DateTime target)
  => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;

If the direction of time is 'negative', the age will be negative also.

One can add a fraction, which represents the amount of age accumulated from target to the next birthday:

public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)
{
  var sign = (source <= target ? 1 : -1);

  var ageInYears = AgeInYears(source, target); // The method above.

  var last = source.AddYears(ageInYears);
  var next = source.AddYears(ageInYears + sign);

  var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;

  return ageInYears + fractionalAge;
}

The fraction is the ratio of passed time (from the last birthday) over total time (to the next birthday).

Both of the methods work the same way whether going forward or backward in time.

Rob
  • 181
  • 5
0

This is a very simple approach:

int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;
0

A branchless solution:

public int GetAge(DateOnly birthDate, DateOnly today)
{
    return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);
}
Wouter
  • 2,540
  • 19
  • 31
0

Don't know why nobody tried this:

        ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);

All it requires is using Microsoft.VisualBasic; and reference to this assembly in the project (if not already referred).

Ruchir Gupta
  • 990
  • 3
  • 10
  • 20
0

Why can't be simplified to check birth month and day?

First line (var year = end.Year - start.Year - 1;): assums that birthdate is not yet occurred on end year. Then check the month and day to see if it is occurred; add one more year.

No special treatment on leap year scenario. You cannot create a date (feb 29) as end date if it is not a leap year, so birthdate celebration will be counted if end date is on march 1th, not on deb 28th. The function below will cover this scenario as ordinary date.

    static int Get_Age(DateTime start, DateTime end)
    {
        var year = end.Year - start.Year - 1;
        if (end.Month < start.Month)
            return year;
        else if (end.Month == start.Month)
        {
            if (end.Day >= start.Day)
                return ++year;
            return year;
        }
        else
            return ++year;
    }

    static void Test_Get_Age()
    {
        var start = new DateTime(2008, 4, 10); // b-date, leap year BTY
        var end = new DateTime(2023, 2, 1); // end date is before the b-date
        var result1 = Get_Age(start, end);
        var success1 = result1 == 14; // true

        end = new DateTime(2023, 4, 10); // end date is on the b-date
        var result2 = Get_Age(start, end);
        var success2 = result2 == 15; // true

        end = new DateTime(2023, 6, 22); // end date is after the b-date
        var result3 = Get_Age(start, end);
        var success3 = result3 == 15; // true

        start = new DateTime(2008, 2, 29); // b-date is on feb 29
        end = new DateTime(2023, 2, 28); // end date is before the b-date
        var result4 = Get_Age(start, end);
        var success4 = result4 == 14; // true

        end = new DateTime(2020, 2, 29); // end date is on the b-date, on another leap year
        var result5 = Get_Age(start, end);
        var success5 = result5 == 12; // true
    }
Sam Saarian
  • 992
  • 10
  • 13
-1

Check this out:

TimeSpan ts = DateTime.Now.Subtract(Birthdate);
age = (byte)(ts.TotalDays / 365.25);
Kols
  • 3,641
  • 2
  • 34
  • 42
mind_overflow
  • 91
  • 1
  • 2
-1

I think this problem can be solved with an easier way like this-

The class can be like-

using System;

namespace TSA
{
    class BirthDay
    {
        double ageDay;
        public BirthDay(int day, int month, int year)
        {
            DateTime birthDate = new DateTime(year, month, day);
            ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
        }

        internal int GetAgeYear()
        {
            return (int)Math.Truncate(ageDay / 365);
        }

        internal int GetAgeMonth()
        {
            return (int)Math.Truncate((ageDay % 365) / 30);
        }
    }
}

And calls can be like-

BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
-2

To calculate the age with nearest age:

var ts = DateTime.Now - new DateTime(1988, 3, 19);
var age = Math.Round(ts.Days / 365.0);
Kols
  • 3,641
  • 2
  • 34
  • 42
Dhaval Panchal
  • 612
  • 4
  • 12
  • 32
-3

A one-liner answer:

DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pratik Bhoir
  • 2,074
  • 7
  • 19
  • 36