-1

In my database the age is 1946 and when we get the log is 2046, we need 1946 as calculate the Global.age. May I ask what wrong with my code? Is that any wrong of my code?

timespan = DateTime.Now.Subtract(Convert.ToDateTime(patientInfo[0].DOB));

Global.age = Convert.ToInt32(timespan.TotalDays) / 365;
log.EventLog("DoB: " + patientInfo[0].DOB);
log.EventLog("Scan Page Age: " + timespan.ToString() + " " + Global.age.ToString());
this.NavigationService.Navigate(Global.bmiPage);
Rob
  • 26,989
  • 16
  • 82
  • 98
Cheah Eng Teong
  • 39
  • 1
  • 2
  • 12
  • depends on what the data is like in DOB column(can you show the values) – Lei Yang Jul 11 '17 at 02:20
  • BTW, you want to get total year with `/365`, but what about the leap year? You may check https://stackoverflow.com/questions/9/calculate-age-in-c-sharp (and ... super old post with ID 9 @_@) – Prisoner Jul 11 '17 at 02:21
  • What do you mean the age is 1946? You mean the year is 1946 – CodingYoshi Jul 11 '17 at 02:23
  • 1
    So you're saying your database is storing 2046 but it should be 1946? Seems like the code you've posted has nothing to do with the issue. – Rob Jul 11 '17 at 02:26
  • Also, re: @Prisoner's point, [this question](https://stackoverflow.com/questions/4638993/difference-in-months-between-two-dates) might be useful. – Kirk Woll Jul 11 '17 at 02:27
  • Debugger is your friend. Just step through it line by line, and find out what the values are for each item of interest. If necessary, create some temp vars and "pour" the values into them, if some of the values are using getters (`patientInfo` looks like a data row, but hard to tell...) – code4life Jul 11 '17 at 02:29

1 Answers1

2

Pass the date of birth to this method and it will return the age:

private static int CalculateAge(DateTime dateOfBirth)  
{  
    int age = 0;  
    age = DateTime.Now.Year - dateOfBirth.Year;  
    if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)  
        age = age - 1;  

    return age;  
}  
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64