0

Can someone please help me write some code to calculate age at a particular date based on date of birth in years.

I'm capturing date of Birth and Date of Diagnosis in database and would like to calculate age in years by Diagnosis date.

partial void AgeAtDiagnosis_Compute(ref string result)
    {
        // Set result to the desired field value

    }
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
user1213055
  • 417
  • 2
  • 5
  • 17

3 Answers3

2
DateTime birth = new DateTime(1950, 01, 01);
DateTime diagnosis = new DateTime(2012, 02, 01);
TimeSpan Span = diagnosis - birth;
DateTime Age = DateTime.MinValue + Span;
// note: MinValue is 1/1/1 so we have to subtract...
int Years = Age.Year - 1;
Schiavini
  • 2,869
  • 2
  • 23
  • 49
1
TimeSpane age0 = this.DateOfDiagnosis - this.DateOfBirth;

int age1 = (int) Math.Trunc( age0.TotalDays / 365.25);
H H
  • 263,252
  • 30
  • 330
  • 514
0

You can just subtract one date from another to give a TimeSpan. That has a TotalDays property from which you can derive years. It depends how accurate you want to be:

var ageInDays = (diagnoticDate - dateOfBirth).TotalDays;  
var age = Convert.ToInt32(ageInDays / 365);

Obviously leap years cause issues so the other alternative is to inspect the year, month and day properties of each date and calculate their differences individually taking into account partial years etc

kaj
  • 5,133
  • 2
  • 21
  • 18