Search code examples
c#fastreport

Calculate Age based on Visit Date


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


Solution

  • 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.