• Home
  • About Me
  • Musings
  • Programming
  • Open Source
  • Computers
  • Society
  • Books
  • Design
  • Movies
  • C#: Calculate Age in Years, Month and Days

    Posted on June 18th, 2009 by Rajeshwaran S P

    Today I was given the task of finding the age of a person, provided the birth date. When I was given the task, I just said, just use the DateDiff function. But it is not that simple.

    One thing I wanted was to keep the code simple and in a few lines of code. Here goes my first iteration.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
             static void CalculateAge()
            {
                DateTime dateOfBirth;
                DateTime.TryParse("02/18/2008", out dateOfBirth);
                DateTime currentDate = DateTime.Now;
     
                TimeSpan difference = currentDate.Subtract(dateOfBirth);            
     
                // This is to convert the timespan to datetime object
                DateTime age = DateTime.MinValue + difference;
     
                // Min value is 01/01/0001
                // Actual age is say 24 yrs, 9 months and 3 days represented as timespan
                // Min Valye + actual age = 25 yrs , 10 months and 4 days.
                // subtract our addition or 1 on all components to get the actual date.
     
                int ageInYears = age.Year - 1;
                int ageInMonths = age.Month - 1;
                int ageInDays = age.Day - 1;
     
                Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);
            }

    But then, there were problems with this method. If the current date is ’06/18/2009′ and the birth date was ’04/18/2000′, it returns, 9 yrs, 2 months and 2 days. The 2 days part is wrong. I didn’t have any clue as to why it appears.

    Then I went down to the basics, using elementary mathematics of subtraction. Here goes the second iteration of the code.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    
            static void CalculateAge2()
            {
                DateTime dateOfBirth = new DateTime(2000, 6, 18);
     
                int ageInYears = 0;
                int ageInMonths = 0;
                int ageInDays = 0;
     
                CalculateAge(dateOfBirth, out ageInYears, out ageInMonths, out ageInDays);
     
                Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays);
            }
     
            ///
            /// Calculate the Age of a person given the birthdate.
            ///
            static void CalculateAge(DateTime adtDateOfBirth, out int aintNoOfYears, out int aintNoOfMonths, out int aintNoOfDays)
            {
                // get current date.
                DateTime adtCurrentDate = DateTime.Now;
     
                // find the literal difference
                aintNoOfDays = adtCurrentDate.Day - adtDateOfBirth.Day;
                aintNoOfMonths = adtCurrentDate.Month - adtDateOfBirth.Month;
                aintNoOfYears = adtCurrentDate.Year - adtDateOfBirth.Year;
     
                if (aintNoOfDays < 0)
                {
                    aintNoOfDays += DateTime.DaysInMonth(adtCurrentDate.Year, adtCurrentDate.Month);
                    aintNoOfMonths--;
                }
     
                if (aintNoOfMonths < 0)
                {
                    aintNoOfMonths += 12;
                    aintNoOfYears--;
                }
            }

    And it works like a charm for all scenarios I throw upon it.

    Scenario 1:
    Current Date : 15 – 09 – 2009
    Birth Date : 09 – 03 – 2000

    Just a difference gives the result
    Age : 6 – 6 – 9 Result is 9 yrs, 6 months, 6 days.

    Scenario 2:
    Current Date : 15 – 09 – 2009
    Birth Date : 28 – 07 – 2000

    Here since 15 – 28 < 0: we borrow one from the month and then add the no of days in the month to the current date. 15 + 30 = 45: 45 – 28 = 17 days
    Then since one month is borrowed: 08 – 07 = 01 months
    Remaining is normal difference
    Age : 17 – 1 – 9 Result is 9 yrs, 1 months, 17 days.

    Scenario 3:
    Current Date : 15 – 09 – 2009
    Birth Date : 28 – 12 – 2000
    Here since 15 – 28 < 0: we borrow one from the month and then add the no of days in the current month to the current date. 15 + 30 = 45: 45 – 28 = 17 days
    Then since one month is borrowed: 08 – 12: So we are supposed to borrow a year and add no of months in current year to current month. 08 + 12 = 20: 20 – 12 = 8 months
    Since a year was borrowed: 2008 – 2000: 8 yrs
    Remaining is normal difference
    Age : 17 – 8 – 8 Result is 8 yrs, 8 months, 17 days.

    But I know there must be better ways to do it. Feel free to drop in code snippets. Comments too are most welcome.

    Possibly Related posts:

    1. Implicit Variable in C# 2008 C# 2008 allows for creating implicit variables using the ‘var’...
    2. C#: Sorting a DataTable Sorting the result in a DataTable’s select command can be...
    3. C#: Null coalescing operator C# has a ?? operator, which is called the ‘Null...

    Tags: ,

    3 Responses to “C#: Calculate Age in Years, Month and Days”

    1. Manikandan said :

      You got extra 2 days since you did not take leap years into account.
      Nice job! Keep rocking :)

    2. Ani said :

      This was the most helpful post I surfed for, most neat and clear. Thanks.

    3. Rajeshwaran S P said :

      Thank you.

    Leave a Reply