How to show a error message if the person is under 18 years old? I use the following code, but it always displays that the age is invalid, even if I enter a date earlier than 1995.
DateTime dt = DateTime.Parse(dob_main.Text);
DateTime dt_now = DateTime.Now;
DateTime dt_18 = dt.AddYears(-18);
if (dt.Date >= dt_18.Date)
{
MessageBox.Show("Invalid Birth Day");
}
You should try something along:
var age = GetAge(dt);
if(age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
int GetAge(DateTime bornDate)
{
DateTime today = DateTime.Today;
int age = today.Year - bornDate.Year;
if (bornDate > today.AddYears(-age))
age--;
return age;
}
Offtopic note: consider naming your variables in such a way, that SO users can guess what is the intention of that variable by reading it. dt dob_main and dt_18 are far away from being good names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With