Hello so I’ve implemented this solution to attain the user’s birthday from a birthday date input:
Calculate age in C#
This works great however I do need to interpret birthday’s for ages less than a year (babies, infants). It will current just give me an age of “0” if there are less than 365 days between the bdate and current date.
What I’m thinking is something like this:
public string calculateAge(DateTime birthDate, DateTime now)
{
//BDay is in different year (age > 1)
int age = now.Year - birthDate.Year;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
if (age == 0)
{
//Bday is in same year
age = now.Month - birthDate.Month;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
return age.ToString() + " months";
}
if (age == 0)
{
//Bday is in the same month
age = now.Day - birthDate.Day;
if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
return age.ToString() + " days";
}
return age.ToString();
}
However some of my test Bdays give me this:
(Today's date: 3/6/2012)
Bday1 = 3/5/2012
Age result = -1
Expected result = 1 day
Bday2 = 3/1/2012
Age result = 0 months
Expected result = 5 days
Bday3 = 1/1/2012
Age result = 2 months
Expected result = 2 months (this is fine)
Bday4 = 3/7/2011
Age result = -1 months
Expected result = 11 months
Bday5 = 3/1/2011
Age result = 1
Expected result = 1 (this is fine)
You can see that because of how it is currently setup the issue is stemming from when the bday month is less than the current month some negative numbers can result.
I also see the error about not being able to get to the “days” loop, but I think that’s a moot point right now. Let me know if you have any insight on what I can do to get the desired results. Also if you need more info like test bdays too. Thanks!
results (for now – 3/7/2012):