By Jeff Atwood

2008-07-31 23:40:59 8 Comments

A given DateTime Type represents a person's birthday.
How could I calculate his / her age in years?


@Alexander Diaz 2020-09-27 06:07:33

int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;
Console.WriteLine("Age {0}", Age);

@CathalMF 2016-04-27 14:58:06

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.

@Aman 2016-12-08 14:13:52

your answer is wrong by one day, it will give the birthday a day before

@Mike Polen 2008-08-04 16:50:06

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.

@JAG 2009-01-22 10:29:38

Just wanted to comment on DateTime.Now performance. If you don't need an accurate time zone value, use DateTime.UtcNow it's much faster.

@Tristan Warner-Smith 2009-07-24 18:04:27

Given we're talking birthdays you can just use DateTime.Today given the time part has no relevance.

@Lars D 2009-11-09 22:09:27

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

@e-satis 2009-11-16 16:35:59

So we have a different age according to different countries and calendar ? What a scoop...

@Shimmy Weitzhandler 2009-12-14 00:37:05

@JAG: DateTime.Today should be even faster.

@Øyvind 2010-11-16 15:37:18

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.

@cdiggins 2011-07-16 17:53:57

The last line made me think too much. Instead how about: if (bday.AddYears(age) > now) age--; This seems to be a more intuitive expression.

@Mike Polen 2011-07-18 18:04:50

Good idea cdiggins, but it doesn't work as bday.AddYears(age) when age is 2/29 returns 2/28 on years that are not leap years...keep trying

@NKCSS 2012-08-16 15:15:54

Or just do if (BirthDate.DayOfYear > Today.DayOfYear); no need to forther modify the date variables

@Guvante 2012-08-21 18:47:47

@NKCSS: That does not handle the leap year correctly. My testing shows that only if (bday > now.AddYears(-age)) works. Since DayOfYear returns 61 in 2012 and 60 in 2011 for March 1.

@devuxer 2012-12-12 02:06:20

@Danvil, is it really wrong? Take a simpler example. Birthday = 2000/02/29, Today = 2001/02/28. Days elapsed: 365. Isn't that one year, and therefore, isn't the person one year old on the 28th? Or is the definition of a year 365-1/4 days? I'm just sayin', it's complicated.

@Nolonar 2013-01-31 10:55:22

Wouldn't it be easier to just do DateTime dateDifference = subject.Birthday - DateTime.Now; int age = dateDifference.Year;? Also, I don't think age depends on leap years. After all, a year is defined as 365<x<366 days, leap years don't make you any day younger.

@Nolonar 2013-01-31 11:03:09

I can't edit my comment anymore, so here's my correction: TimeSpan difference = subject.Birthday - DateTime.Now; int age = difference.Days; If you want the age in years, you could always add int ageInYears = age / 365;

@cja 2013-02-13 15:08:20

@LarsD "Several countries have skipped dates after the birth of current living people" <- What do you mean?

@bPratik 2013-02-14 18:04:55

@cja - It means that some countries did some funnies years ago to sync up calendars and remove discrepancies! may speak more about it, I haven't fully read. The reference to 'Current People' is simply to state that the adjustments happened in the 20th century (1901-2000). A lot of people are still alive from that period! :)

@Shaik Raffi 2013-11-05 11:34:11

DateTime birthdate = new DateTime(2012, 11, 5); DateTime now = DateTime.Now; int years = now.Year - birthdate.Year; if (now.Month < birthdate.Month || (now.Month == birthdate.Month && now.Day < birthdate.Day)) years--; Console.WriteLine(years.ToString()); Console.ReadLine();

@Gusdor 2013-11-05 13:04:37

@LarsD so what you are saying is that there is no way to calculate people's ages? Rubbish. They messed with their calendar, they can adapt. Even if you could do a library to calculate cross calender based on locale, a) where do you source this info b) is it actually worth it?

@Dhaval Panchal 2013-12-03 10:13:16

This code is not calculating the nearest age. Here, is the code: var ts = DateTime.Now - new DateTime(1988, 3, 19); var age = Math.Round(ts.Days / 365.0);

@Travis 2014-05-17 00:02:51

int age = DateTime.Today.Year - bday.Year; age = bday > DateTime.Today.AddYears(-age)) ? age-- : age;

@galdin 2015-06-08 17:26:27

why not use TimeSpan?

@alpham8 2015-07-11 17:23:13

is this solution also looking about months? Otherwise it clould +/- 1 year

@Luke T O'Brien 2015-08-14 08:52:16

This answer doesn't take month into account - If I was born in December 1990 and today is March 2000 my age is 9 and not 10 because I haven't had my birthday yet

@user743382 2015-10-12 07:38:26

@LukeTO'Brien The if (bday > today.AddYears(-age)) age--; part in this answer is supposed to take care of that. age would be 10 at that point based on the difference in year numbers. If the birthday (December 1990) is later than 10 years ago (which would be March 1990), which it is, then age gets decremented to 9. Are you saying that doesn't work for you?

@Rob 2015-12-04 02:31:31

@TristanWarner-Smith Well, technically it does. If you're born Jan 1st 1990 at 1pm, you're 0 at Jan 1st 12:59 1991, but 1 at Jan 1st 1:01pm 1991.

@Tristan Warner-Smith 2015-12-04 10:17:59

@Rob I guess you're right, but it's a question of precision, usually your birthday counts as any time from 00:00 - 23:59:59 on a specific day.

@displayName 2016-03-11 16:48:41

Quick Fun Fact: This answer has featured in this pluralsight course's, Module 5 - Chapter 3.

@jfren484 2016-07-12 16:56:37

@Rob In the USA, at least, it is accepted that on your birthday, no matter when in the day you were born, you are said to be the next age in years. Even if one was born at 11:59 pm on January 1, at the New Year's party when the ball drops, everyone would accept that your age had changed even though you are still almost 24 hours short of the time of your birth. :) Legally, an individual is said to be a year older on their birthday as well. Whether it's being 16 to drive, or 21 to drink, or 18 to vote. It doesn't matter what time you were born. On your birthday you're a year older.

@Daniel Liuzzi 2016-09-05 14:14:39

In England and Wales or in Hong Kong, a person born on February 29 will have legally reached 18 years old on March 1. If he or she was born in Taiwan he or she legally becomes 18 on February 28, a day earlier. (Wikipedia) So birthdate.AddYears(age) > today and birthdate > today.AddYears(-age) are both correct and incorrect, depending on the jurisdiction.

@Legends 2017-10-11 19:42:14

Is this solution above with over 1400 upvotes correct, because I can read from the comments section that there are some issues with this solution...?

@user743382 2018-02-22 12:11:14

@Legends It's making more assumptions than have been pointed out in the answer, and it's correct for your case if and only if those assumptions hold for your case. Without knowing your case, it's impossible for anyone other than yourself to turn that into a yes or no answer.

@Christian Findlay 2018-04-09 02:48:58

The concept of measuring age in years is just a filthy lie because it doesn't take in to account leap years. We should be measuring age in days.

@Nathan Cooper 2018-06-11 15:37:24

If it's your 30th birthday this afternoon, are you 30 in the morning? I would say yes. Which means it should be if (birthdate.Date > today.AddYears(-age).Date) age--;?

@Mr. Leeds 2018-06-28 03:45:29

This kind of answer not only answers your question. It also leaves another question. I didn't know about that East Asian Reckoning until i found this answer.

@Wouter 2018-11-26 00:27:37

Note that this requires both datetime values to be on the same timezone.

@nardnob 2020-03-17 18:38:48

If using this you might also validate that birthdate is > DateTime.Today, otherwise you can get a negative age. It's a feature?

@user1210708 2015-06-24 11:26:39

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)
            days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;

        if (months < 0)
            months = 12 + months;

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

And here is a unit 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));

@musefan 2012-02-24 12:58:54

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

return age;

Let us know if you spot any problems ;)

@Alexander 2020-03-05 08:37:04

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;
                add = -1;
            add = -1;
        int age = now.Year - dob.Year + add;

@Suraj Kumar 2020-03-05 09:04:50

There should be a description of your answer for the OP as well as for the future readers.

@Võ Quang Hòa 2020-04-15 03:42:26

Your code is not simple, it's a mess. I would write this, maybe you don't belive it but the code below does the samething (now - dob).Year

@Nick Berardi 2008-08-01 12:07:19

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

@Michael Stum 2008-08-01 21:46:12

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

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

@webdad3 2016-11-09 22:06:26

This appears to handle different regions (date formats) the best.

@James Curran 2008-10-03 20:19:31

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

@MusiGenesis 2009-08-01 16:03:00

I don't think Harry Patch would have appreciated your spot-testing methodology:…

@mpen 2010-08-12 05:28:07

Google says days in a year = 365.242199

@dan04 2010-10-06 02:01:06

The average length of a year in the Gregorian Calendar is 365.2425 days.

@Peter Perháč 2011-03-09 12:07:33

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.

@ChadT 2011-03-25 05:27:55

^^ Because sometimes it's important. In my testing this fails on the persons birthday, it reports them younger than they are.

@Dave Cousineau 2016-01-01 20:51:50

this is what I would start with, too, but testing it, it often gets a person's birthday wrong.

@myusuf3 2016-11-07 17:55:29

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

@krowe2 2018-11-21 15:44:01

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

@Peter Mortensen 2020-02-29 01:26:02

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

@SillyMonkey 2009-05-18 12:36:51

Here's a one-liner:

int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;

@Kjensen 2011-02-05 21:42:19

This is broken. Made testable: public static int CalculateAge(DateTime dateOfBirth, DateTime dateToCalculateAge) { return new DateTime(dateToCalculateAge.Subtract(dateOfBirth).Ticks).Yea‌​r - 1; } ...Gives age 14 when I input 1990-06-01 and calculate the age on the day BEFORE his 14th birthday (1990-05-31).

@RMA 2009-10-20 15:07:22

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

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

    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)) 
    // Don't use:
    // if (birthDate.AddYears(age) > now) 
    //     age--;

    return age;

@Matt Johnson-Pint 2014-08-17 05:44:53

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. So while your code is not "wrong", neither is the accepted solution.

@Sergiu Mindras 2014-11-05 09:20:23

public int CalculateAgeCorrect(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; if (now.Month > birthDate.Month) return age; if (now.Month < birthDate.Month) return age - 1; // now.Month == birthDate.Month if (now.Day < birthDate.Day)) return age - 1; return age; }

@Mike Polen 2014-12-31 15:32:43

Revisionist history has touched me :-) I had tests and did TDD but did not post bqck in 2008. Shame on me as i left them on my hard drive when I quit. I love that this quesion asked and answered during the so beta. Answered by me cuz I was bored at work has taken on a life of its own. It really shows the power stack overflow.

@Chris Hawkes 2014-12-31 20:00:52

While this is a great solution, you're screwed for unit testing if the Date of the unit test is the 31st. At least that is my assumption after digging into this problem for at least an hour.

@kpull1 2015-10-20 09:19:36

Which method is right and which is wrong is subjective, some leaplings celebrate on 1st of March and others on 28th of February. Font:

@jfren484 2016-07-12 17:18:36

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

@Matt Johnson-Pint 2016-07-12 19:26:17

@jfren484 - read the Wikipedia article. It varies considerably across jurisdictions.

@jfren484 2016-07-13 00:53:49

@MattJohnson I did read it, and I understand that. I'm saying the locations that use March 1 as the day to advance the age of someone born on Feb 29 in a non-leap year seems more correct from a philosophical point of view.

@Disillusioned 2017-03-04 10:06:22

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

@jfren484 2017-03-04 18:45:13

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

@Anonymous Coward 2017-11-09 13:10:24

@jfren484 The way age should be treated is : 1.- Legally if law matters. 2.- If precission matters use seconds or any other unit wich is an unambiguous unit rather than years which is ambiguous (1 year can be understood as 365 days, or 366 or 360 or 365.25 or 365.2425 or...) 3.- If neither law nor precission matters it is fine to use your way or Craig's way or many others, it does not matter and none is better. --- Since this question asks for "age in years" (ambiguous unit) without further specifics I would say we are in case 3.

@Infomorph 2018-11-13 12:04:59

Thas exacly like i would do it. You have to consider month and day. var reachedDateOfYear = b.Month >= a.Month && b.Day >= a.Day; var yearDifference = (b.Year - a.Year) + (!reachedDateOfYear?-1:0);

@Wouter 2018-11-25 23:38:56

Regarding this 'philosophical' point. A leap year adds 1 one day every 4 years for everybody. You can only age 4 years every 1461 days. It doesn't matter if you are born on this leapday. If you are born on yyyymmdd 20000129 you need 366 days to age 1 year. Why would a person born on 20000229 age 1 day earlier? Also summing age over a 1491 day window will be off by 3 days when aging 28th feb. If you want these numbers to align the birthday should be on the the 1st of march. (Legally you can define whatever you need. You can age on the 1st of jan. Your pension starts on the 1st of a month.)

@Wouter 2019-06-26 15:20:26

The implementation of CalculateAgeWrong2 is wrong. You need: if (birthDate > now.AddYears(-age)) age--;

@Little geek 2020-01-28 10:25:31

For the leap day discussion: The leap day is actually the 24th of February. Notice that in countries that have name days (like in Denmark) the names of the 24-28 in a non-leap year are shifted in a leap year because the extra day is inserted before the 24th.

@azamsharp 2009-11-28 01:58:57

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;

@Chris Shouts 2010-05-04 20:57:07

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?"

@azamsharp 2010-05-05 00:03:59

How did that happen? I don't even remember putting IsValid as object. It should be DateTime!

@T_Bacon 2018-03-28 08:41:56

Instead of the if statement, why not use return yearsOld > 18;

@Archit 2013-09-19 13:15:37

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?

@Casey 2014-10-14 20:47:18

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.

@vulcan raven 2013-09-08 11:01:48

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 2020-02-29 01:11:09

It is today! (The next one is four years from now.)

@Pratik Bhoir 2014-07-29 11:46:24

A one-liner answer:

DateTime dateOfBirth = Convert.ToDateTime("01/16/1990");
var age = ((DateTime.Now - dateOfBirth).Days) / 365;

@mjb 2014-10-23 13:18:40

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)

    return age;

@Peter Mortensen 2020-02-29 01:06:52

It is today! (The next one is four years from now.)

@tif 2020-08-18 11:04:47

You can use DateTime.Today instead, since time does not matter for the calculation

@Lukas 2015-06-26 16:00:29

It can be this simple:

int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;

@VhsPiceros 2015-10-05 17:09:38

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

@André Sobreiro 2016-09-29 20:13:16

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;

@Sean Kearon 2017-07-16 10:39:21

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

@mind_overflow 2015-05-09 22:03:15

Check this out:

TimeSpan ts = DateTime.Now.Subtract(Birthdate);
age = (byte)(ts.TotalDays / 365.25);

@Kaval Patel 2017-10-31 12:09:08

To calculate how many years old a person is,

DateTime dateOfBirth;

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

if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;

@Tobias 2018-06-26 06:32:15

This would mean that someone born on December 31st in 2000 turned 18 on January 1st 2018! 2018-2000 = 18

@Kaval Patel 2018-07-25 12:01:01

Thanks for reminding me I have updated my answer now, at that time I am forgetting to add the last line. So Thank you for correcting me. :)

@sensei 2019-06-10 18:45:10

you just copied first answer, what gives Patel?

@BrunoVT 2015-07-02 07:37:49

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.

@Edward Olamisan 2015-10-02 16:57:58

It's wrong. In your code age would be a TimeSpan. Not DateTime.

@Arturo Torres Sánchez 2015-10-06 15:17:47

The problem with this is that an age like “17 years” doesn't translate directly to a TimeSpan because you don't know which of those 17 years were leap years.

@dav_i 2015-02-17 17:24:51

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

    return age;

@Narasimha 2012-07-04 11:28:23

Try this solution, it's working.

int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - 
           Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000;

@Moises Conejo 2017-12-15 17:27:13

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

@Wiktor Zychla 2018-06-27 08:32:36

What about leap years?

@Moshe L 2012-01-11 08:58:06

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

@Protiguous 2020-06-05 10:20:52

The question asks for, "In C#, how do I calculate someone's age...".

@Moshe L 2020-06-06 17:32:31

c# and vb is the same for this idea.

@user9359822 2018-02-15 11:17:51

var birthDate = ... // DOB
var resultDate = DateTime.Now - birthDate;

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

@Ahmed Sabry 2015-10-12 13:12:02

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

@BigJim 2008-09-26 20:07:37

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";

@James Curran 2008-10-03 20:13:25

Nope. TimeSpan as Days, but no Months or Years

Related Questions

Sponsored Content

18 Answered Questions

39 Answered Questions

[SOLVED] Should I use the datetime or timestamp data type in MySQL?

17 Answered Questions

[SOLVED] C# DateTime to "YYYYMMDDHHMMSS" format

  • 2010-06-11 18:43:49
  • 1447984 View
  • 639 Score
  • 17 Answer
  • Tags:   c# datetime

40 Answered Questions

37 Answered Questions

[SOLVED] Calculate relative time in C#

44 Answered Questions

[SOLVED] How do I create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 1126852 View
  • 1925 Score
  • 44 Answer
  • Tags:   c# .net excel file-io

12 Answered Questions

[SOLVED] Calling the base constructor in C#

27 Answered Questions

[SOLVED] Why not inherit from List<T>?

43 Answered Questions

[SOLVED] How to return only the Date from a SQL Server DateTime datatype

Sponsored Content