如果此人未满18岁,如何显示错误消息?我使用以下代码,但它始终显示年龄无效,即使我输入的日期早于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");
}
答案 0 :(得分:8)
你应该尝试一下:
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:考虑以这种方式命名变量,SO用户可以通过读取来猜测该变量的意图。 dt
dob_main
和dt_18
远远不是好名字。
答案 1 :(得分:6)
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");
}
答案 2 :(得分:3)
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");
}
答案 3 :(得分:2)
DateTime? BirthDate = DateTime.Parse(dob_main.Text);
if (BirthDate < DateTime.Now.AddYears(-18))
{
MessageBox.Show("Invalid Birth Day");
}
答案 4 :(得分:0)
简单使用这种方式
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");
}
答案 5 :(得分:0)
一个人可以通过在解析日期后简单地使用以下代码来实现此目的:
private static bool GreaterThan18(DateTime bornIn)
{
return (bornIn.AddYears(18) >= DateTime.Now);
}
答案 6 :(得分:0)
尝试一下:
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;
}
引用:https://naveed-ahmad.com/2010/01/08/calculating-age-from-date-of-birth-c/
答案 7 :(得分:0)
尝试一下:
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;
}
}
}