1

I need to write C# code to calculate a person's age based on a birthdate and a fixed exam visit date.

Currently the code is written like this:

public static int CalculateAge(string birthdate)
{
  DateTime dob = DateTime.Parse(birthdate);

  int age = DateTime.Now.Year - dob.Year;
  if (DateTime.Now.Month < dob.Month)                         
  {
    age--;
  }
  else if (DateTime.Now.Month == dob.Month &&
    DateTime.Now.Day < dob.Day)
  {
    age--;
  }

  return age;
}

I need to pass in a second variable called ExamDate to figure out the age. The way it is currently written, when the FastReport is run say 3 years down the road, obviously someone who is 22 now would be 25 when the report is displayed. I know we can't use DateTime.Now

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
elderboy02
  • 27
  • 5
  • "I know we can't use DateTime.Now" - why not? And if not, why *do* you use it then? – Thomas Weller Sep 23 '15 at 19:03
  • Sorry, I guess we can use DateTime.Now. I am new to C# coding. I was trying to say that we don't want the worker's age to change if we were to open the report in the future. – elderboy02 Sep 23 '15 at 19:05
  • Can you not add a second parameter? So, `CalculateAge(string birthDate, string visitDate)`. – code4life Sep 23 '15 at 19:06
  • Ok, now I see. You want something like `CalculateAge(string birthdate, string examdate)` – Thomas Weller Sep 23 '15 at 19:06
  • Correct. For example, a patient has a birthdate of 1/2/92 and was seen on 9/4/15. His age is 23 years old. If I were to open the report again next year, his age will be 24 which is incorrect since he had the exam when he was 23 years old. All of his test results for subsequent tests will change as well next year and we don't want that to happen. – elderboy02 Sep 23 '15 at 19:09
  • Personally I'd recommend passing `DateTime` instead of `string` and do the parsing wherever the `string` enters the system. – juharr Sep 23 '15 at 19:14

1 Answers1

3

Pass the second date as parameter, and change all occurrences from DateTime.Now to this date:

public static int CalculateAge(string birthdate, string examDate)
{
  DateTime dob = DateTime.Parse(birthdate);
  DateTime ed = DateTime.Parse(examDate);

  int age = ed.Year - dob.Year;
  if (ed.Month < dob.Month)                         
  {
    age--;
  }
  else if (ed.Month == dob.Month &&
    ed.Day < dob.Day)
  {
    age--;
  }

  return age;
}

So when you will pass person date of birth and date of the exam, the result will be always the same.

jjczopek
  • 3,319
  • 2
  • 32
  • 72