Reputation: 47
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");
}
Upvotes: 2
Views: 26639
Reputation: 1142
Try this:
DateTime birthDate = DateTime.Parse(dob_main.Text);
if (IsAgeLessThan18Years(birthDate))
{
MessageBox.Show("Invalid Birth Day");
}
bool IsAgeLessThan18Years(DateTime birthDate)
{
if (DateTime.Now.Year - birthDate.Year > 18)
{
return false;
}
else if (DateTime.Now.Year - birthDate.Year < 18)
{
return true;
}
else //if (DateTime.Now.Year - birthDate.Year == 18)
{
if (birthDate.DayOfYear < DateTime.Now.DayOfYear)
{
return false;
}
else if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
{
return true;
}
else //if (birthDate.DayOfYear == DateTime.Now.DayOfYear)
{
return false;
}
}
}
Upvotes: 0
Reputation: 1035
try this:
private static int CalculateAge(DateTime dateOfBirth)
{
int age = 0;
age = DateTime.Now.Year - dateOfBirth.Year;
if (DateTime.Now.DayOfYear < dateOfBirth.DayOfYear)
age = age - 1;
return age;
}
refer: https://naveed-ahmad.com/2010/01/08/calculating-age-from-date-of-birth-c/
Upvotes: 0
Reputation: 5689
One can achieve this by simply using this after parsing the date:
private static bool GreaterThan18(DateTime bornIn)
{
return (bornIn.AddYears(18) >= DateTime.Now);
}
Upvotes: 1
Reputation: 21
DateTime? BirthDate = DateTime.Parse(dob_main.Text);
if (BirthDate < DateTime.Now.AddYears(-18))
{
MessageBox.Show("Invalid Birth Day");
}
Upvotes: 2
Reputation: 610
Simple use this way
DateTime BirthDate = DateTime.Parse(dob_main.Text);
DateTime CurrentDate = DateTime.Today;
int Age = CurrentDate.Year - BirthDate.Year;
if(Age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
Upvotes: -1
Reputation: 23626
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.
Upvotes: 8
Reputation: 1785
DateTime dt = DateTime.Parse(dob_main.Text);
DateTime dt_now = DateTime.Now;
DateTime dt_18 = dt.AddYears(18); //here add years, not subtract
if (dt_18.Date >= dt_now.Date) //here you want to compare dt_now
{
MessageBox.Show("Invalid Birth Day");
}
Upvotes: 7
Reputation: 63065
DateTime bday = DateTime.Parse(dob_main.Text);
DateTime today = DateTime.Today;
int age = today.Year - bday.Year;
if(age < 18)
{
MessageBox.Show("Invalid Birth Day");
}
Upvotes: 5