0
string birthDay = "";      
_birthDay = DateTime.Parse(this.BirthDay.Value.ToString()).ToString("yyyyMMdd");
                    DateTime today = DateTime.Today;
                    int age = today.Year - _birthDay.Year;
                    if (_birthDay > today.AddYears(-age)) age--;
    txtbox1.Text = age;

It seems error, How to calculate age from birth day?

Solution
  • 164
  • 1
  • 2
  • 11
  • Are you indicating that you are encountering an error? If so, what is the error? – Anthony Forloney Dec 09 '15 at 01:49
  • Why are you setting `_birthDay` to the string representation of the date, and then using it to compare to another date? Remove `.ToString("yyyyMMdd");` – Rob Dec 09 '15 at 02:04

3 Answers3

1
int age = (DateTime.Today - _birthDay ).TotalDays;

if you want the difference in years you can refer this thread

TimeSpan span = DateTime.Today - _birthDay;
// because we start at year 1 for the Gregorian 
// calendar, we must subtract a year here.
int age = (zeroTime + span).Year - 1; 
Community
  • 1
  • 1
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

If you want to calculate it very precision try below:

The most important thing is How many days left since you born.

the 2nd important things is how many years left since you born.

But...not every year is 365 days always.you have to consider the condition about leap year.

give you a clue:if your age is 25,assume every year is 365 days,so the days left is 365*25+x(1<=x<=365)..etc..

MapleStory
  • 628
  • 3
  • 11
  • 22
0

see: Calculate age in C#

But you have to ask yourself about the necessary precision since timezones will affect this. In very rare cases there will some ambiguity. For example, If it's your birthday and you commit a crime when you're 17 in one timezone but 18 in another there's going to be an issue. If the answer is critical then you will need to provide some sort of message back to your user to explain some of the vagaries of computing age.

Community
  • 1
  • 1