My application needs to adjust a clients current age by +0.5 if it has been 6 months since their last birthday.
The code should look something like this, but how many ticks would there be in 6 months?
if (DateTime.Today - dateOfBirth.Date > new TimeSpan(6))
{
adjust = 0.5M;
}
else
{
adjust = 0M;
}
Thanks in advance
EDIT: You know what, actually? Since clearly what you really need is just to display the user’s age to within 6 months, this is what you should really do.
The above code includes a big comment explaining its own shortcomings, helpfully pointed out by David.
Now, here’s yet another option. It’s kind of ugly because it uses a loop; but it’s also more rock-solid since it utilizes the DateTime.AddMonths method, which has the advantage of having already been tested and documented by Microsoft.
This idea that people have been suggesting of checking
dateOfBirth.AddMonths(6)is wrong. SincedateOfBirthis a DateTime, it represents the user’s birth date, not their birth day.What you want to check is if six months have elapsed since the user’s last birthday–not the date they were born. Here’s one way to do that: