0

Possible Duplicate:
Calculating age from birthday

How do you calculate age in years, taking input from TextBox in the format dd/MM/yyyy?

e.g.

input: txtDOB.Text 20/02/1989 (String format)
output: txtAge.Text 23

Community
  • 1
  • 1
user1557308
  • 83
  • 2
  • 4
  • 13
  • Please view this link http://stackoverflow.com/questions/9/c-calculating-age-from-birthday – Amol Kolekar Jul 30 '12 at 07:40
  • I checked it. everything there is assuming the input is in DateTime format, I am stuck at conversion from textbox to DateTime in the format dd/mm/yyyy – user1557308 Jul 30 '12 at 07:55
  • You can use Convert.ToDateTime(TextBox1.Text).ToString("dd/MM/yyyy") or DateTime.TryParseExact(TextBox1.Text, "dd/MM/yyyy", null, System.Globalization.DateTimeStyles.None) – Amol Kolekar Jul 30 '12 at 08:06
  • Hey man, we need your opinion. How will you use any approach below? From medical perspective my approach is incorrect, from users perspective - 50\50. I think if you need precise calculation you should use Matten's approach and play with the ratio. Also I would suggest you to show months along with years to avoid confusion from user pov. You see fit – Madman Jul 30 '12 at 09:18
  • The obvious answer is that you increase in age by a year on your birthday... at least, that's how I think most people think birthdays work. :) That does mean that if you're born on a leap day you must wait until 1st March for your birthday! It also means that if you are born on 1st March, then you still celebrate your birthday on 1st March during a leap year - you don't celebrate it on Feb 29th. – Matthew Watson Jul 30 '12 at 14:49

7 Answers7

3

You can use the Substract method of DateTime (link) and then use the Days property to determine the actual age:

DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);

int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
Matten
  • 17,365
  • 2
  • 42
  • 64
  • Ignoring years where the number of days isn't 365 – Steen Tøttrup Jul 30 '12 at 07:42
  • Downvoted because it fails for some inputs. – Matthew Watson Jul 30 '12 at 08:08
  • @Matthew Watson - Could you please give me an example? – Matten Jul 30 '12 at 08:09
  • Sure: DOB = 1964-03-16, TODAY = 2013-03-16. Age should be 49, but your code gives 48. – Matthew Watson Jul 30 '12 at 08:39
  • @MatthewWatson Ok agree, adjusted on base of the astronomic year. – Matten Jul 30 '12 at 08:49
  • 1
    I'm not sure that usage of magic like '365.24219' is good solutions. – Madman Jul 30 '12 at 08:54
  • It's not magic, it's a constant, known as the astronomic or tropican year. Wikipedia: "Some exceptions to this rule are required since the duration of a solar year is *slightly less* than 365.25 days" – Matten Jul 30 '12 at 08:56
  • @Madman in general I'd totally agree with you, magic numbers are no good; but in this case I would use this as input, because it is the current mean solar year *and* it has a great advantage -- returning the right age until you're 36500 years old (based on the way you're calculating the "right" age) :-) – Matten Jul 30 '12 at 09:00
  • @Matten Man, I think finally you'll win in spite of magic ;) Until calendar will not changed your approach will work, so I give You my point. – Madman Jul 30 '12 at 09:24
  • Such an easy question and no nice answer to go :-) – Matten Jul 30 '12 at 09:28
  • Uhm, why not just `new DateTime( DateTime.Now.Subtract( givenDate ).Ticks ).Year` ? – Dai Jul 30 '12 at 12:17
  • Hate to say this, but the amended code *still* doesn't work. It doesn't account for leap years properly, so the following is wrong: DOB = 1963-03-01, NOW = 2016-02-29, AGE = 53 (should be 52) – Matthew Watson Jul 30 '12 at 14:37
0

As already noted in a comment, the correct answer is here: Calculate age in C#

You just need to get the birthday as a DateTime:

DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Community
  • 1
  • 1
Steen Tøttrup
  • 3,755
  • 2
  • 22
  • 36
0
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25;  // 365 1/4 days per year
Sanket R. Patil
  • 311
  • 1
  • 2
  • 8
  • 1
    This will fail to give the right answer in many circumstances. – Matthew Watson Jul 30 '12 at 08:02
  • Also, `365.25` is an incorrect value. Leap years are *not* precisely every four years. Years ending in `00` are not leap years unless their hundreds/thousands/etc are also divisible by 4. So, 1900 was not a leap year, but 2000 was. – Andrew Barber Jul 30 '12 at 13:21
0

The following will work once you have parsed the birth date into a DateTime:

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

Parse the date like so:

DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);

And a sample program:

using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dob = new DateTime(2010, 12, 30);
            DateTime today = DateTime.Now;

            int age = AgeInYears(dob, today);

            Console.WriteLine(age); // Prints "1"
        }

        static int AgeInYears(DateTime birthday, DateTime today)
        {
            return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
  • Why is this downvoted? It has been well-tested and gives the correct answer for all inputs. It's pointless to downvote something without giving a reason. – Matthew Watson Jul 30 '12 at 08:05
  • 1
    This doesn't work. Try with the sample value: `12/30/2010` for the date of birth and todays date for `today`. It returns `2011`... -1 – dtsg Jul 30 '12 at 08:09
  • No, it correctly returns 1. Why not actually try it? It's definitely correct, and it absolutely certainly works with 2010-12-31 for DOB and 2012-07-30 for today. – Matthew Watson Jul 30 '12 at 08:13
  • I did... It gives the result `2011`. – dtsg Jul 30 '12 at 08:16
  • It really doesn't... How are you calculating it? I've added a sample program to the OP. Please compile and run it. You WILL see that the result is 1. – Matthew Watson Jul 30 '12 at 08:19
  • You're assuming that the datetime is always in that format... – dtsg Jul 30 '12 at 08:20
  • "You're assuming that the datetime is always in that format": What are you talking about? What format? I'm using DateTime - it HAS NO FORMAT! – Matthew Watson Jul 30 '12 at 08:21
  • 1
    The date of birth? It will be coming from the user through a textbox so won't necessarily be in the format of YYYY/MM/dd... – dtsg Jul 30 '12 at 08:22
  • 1
    My code is not parsing the string since that has already been solved in other comments. My code just calculates the age in years using DateTime objects. The format is therefore irrelevant. The code does work. You clearly haven't actually tried it. – Matthew Watson Jul 30 '12 at 08:24
  • Read the OP's comments: `I checked it. everything there is assuming the input is in DateTime format, I am stuck at conversion from textbox to DateTime in the format dd/mm/yyyy`. This answer doesn't meet the criteria. – dtsg Jul 30 '12 at 08:28
  • I've now added the parsing code to my original reply. The parsing code had already been given though - I was just adding the code to actually calculate the age, since all the other posted code was wrong. Notwithstanding the parsing part, the algorithm I posted is definitely correct. – Matthew Watson Jul 30 '12 at 08:43
  • 2
    What's the 372 magic number about? – R. Martinho Fernandes Jul 30 '12 at 11:23
  • More details here: http://social.msdn.microsoft.com/Forums/is/csharplanguage/thread/ba4a98af-aab3-4c59-bdee-611334e502f2, but it's the number of days that there would be in a year if all months had 31 days. – Matthew Watson Jul 30 '12 at 14:30
-1

This answer isn't the most efficient as it uses a loop, but it doesn't rely on using 365.25 magic numbers either.

A function to return the whole number of years from a datetime to today:

public static int CalcYears(DateTime fromDate)
    {
        int years = 0;
        DateTime toDate = DateTime.Now;
        while (toDate.AddYears(-1) >= fromDate)
        {
            years++;
            toDate = toDate.AddYears(-1);
        }
        return years;
    }

Usage:

int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • That doesn't work... The loop always exits immediately so that it always returns 0 if fromDate is more than 1 year before toDate. – Matthew Watson Jul 30 '12 at 14:42
  • @MatthewWatson - thanks I converted the code from VB but didn't test it before posting - should now work. – Matt Wilko Jul 30 '12 at 15:02
-2
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
Madman
  • 3,171
  • 2
  • 32
  • 44
  • If you are born at newyear than you are not 1 year old the next day. – brano Jul 30 '12 at 07:47
  • 2
    Born: 12/31/1989, Today: 1/1/1990. 1990-1989 = 1 – Matten Jul 30 '12 at 08:08
  • 1
    OK. Did you see the Person with 0 years old ? I agree that formally your example is correct, but from user perspective I think it is not. – Madman Jul 30 '12 at 08:31
  • 1
    Ok. Born 12/31/1989, Today 1/1/2012. Calculated age is 23, actual age is 22. – Matten Jul 30 '12 at 08:44
  • 1
    Matten is correct: This code is very definitely wrong. – Matthew Watson Jul 30 '12 at 08:49
  • 1
    Well, I think we need topic starter's opinion, what solutions fit his needs and then make corrections to the answer – Madman Jul 30 '12 at 08:50
  • 1
    Without using the current date, the error that @Matten pointed out is always going to happen in some form or another. One should instead measure the elapsed time between the DoB and today, then calculate the years from there. – 2v0mjdrl Jul 30 '12 at 08:52
  • @MatthewWatson - thanks. i completely missed that. can u suggest a way, with similar code, so that if the age is 22 yrs 6 mnths, the output is 22. but if it is 22 yrs 7 mnths, the output is 23. Otherwise the code works fine with me – user1557308 Jul 30 '12 at 10:44
  • You could use the code I posted in my answer (see the AgeInYears() function) - it always gives the right answer (We use it in our production code, and it's been extensively tested. I didn't write it myself though, I got it from a programming forum.) – Matthew Watson Jul 30 '12 at 14:47
-3

Try this

string[] AgeVal=textbox.text.split('/');
string Year=AgeVal[2].tostring();
string CurrentYear= DateTime.Now.Date.Year.ToString();
int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year));

Subtract the two values and get your age.

Bart
  • 19,692
  • 7
  • 68
  • 77
user1528573
  • 95
  • 1
  • 2
  • 9