验证年龄不低于18岁

Ada*_*dax 1 c# sql validation datetimepicker

如果此人未满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");
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*nov 7

你应该尝试一下:

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;
}
Run Code Online (Sandbox Code Playgroud)

Offtopic note:考虑以这种方式命名变量,SO用户可以通过读取来猜测该变量的意图.dt dob_maindt_18远离是好名字.


Dam*_*ith 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");
}
Run Code Online (Sandbox Code Playgroud)


VsM*_*MaX 5

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");
}
Run Code Online (Sandbox Code Playgroud)