I'm trying to convert a personnel's date of birth to their actual age within a ViewModel inside of another viewmodel I plan on calling in the front end.
I've managed to create public DateTime? PersonnelDOB { get; set; }
and it's bringing back their Date of Birth I.E 6/12/1972
I need to convert this to their actual age so instead of 6/12/1972, it'll be "48 years old"
the issue to this current problem is that 'dob' is a DateTime and 'today.year' is an int. I can't subtract a DateTime from an int. I need to also make sure I account for leapyears and for it to actually accurately output their age. I also will want to check that dob isn't null. I dont have to do this within a viewmodel I created, it was just an avenue I was exploring. Thank you all for your help!
public DateTime? PersonnelDOB { get; set; }
public PersonnelDOBViewModel()
{
var dob = PersonnelDOB;
// Save today's date.
var today = DateTime.Today;
// Calculate the age.
var age = today.Year - dob;
// Go back to the year the person was born in case of a leap year
if (dob > today.AddYears(-age)) age--;
return age;
}
** A coworker helped me out and for those of you interested in the right answer - here it is
public DateTime? PersonnelDOB { get; set; }
public int? PersonnelAge
{
get
{
if (!PersonnelDOB.HasValue)
return null;
DateTime today = DateTime.Today;
int years = today.Year - PersonnelDOB.Value.Year;
years -= (today.Month < PersonnelDOB.Value.Month || (today.Month == PersonnelDOB.Value.Month && today.Day < PersonnelDOB.Value.Day)) ? 1 : 0;
return years;
}
}