ChathurawinD
ChathurawinD

Reputation: 784

How to check selected value of datetime picker to be in some value range?

I want to select a date from a date time to be in a specific time range. I want to select a user's birthday in my datetime picker. I want to add only the users of age between 18-100 years. I want to check whether selected value of my datetime picker is greater than 18 years from today's date and selected value of date time picker less than 100 years from today's date. I tried this, but it gives me wrong output.

        if (dtpDOB.Value<DateTime.Today.AddYears(-18)&& dtpDOB.Value>DateTime.Today.AddYears(-100))
        {
            //
        }

Upvotes: 0

Views: 2271

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Simple Boolean conditions can be confusing sometimes (I also submitted a wrong answer at first but immediately deleted it). Your condition was correct for determining if the date was OK:

if (dtpDOB.Value < DateTime.Today.AddYears(-18)
    && dtpDOB.Value > DateTime.Today.AddYears(-100))
{
    // the date entered was valid!
}

You can put an else block after that and handle the unwanted input there.

Note that you check for the "left" endpoint of the interval last. Today minus 100 years is the earlier of the two points in time.

I think you wanted to express the negation. That is like this:

if (!(dtpDOB.Value < DateTime.Today.AddYears(-18)
    && dtpDOB.Value > DateTime.Today.AddYears(-100)))
{
    // the date entered was bad, outside permitted range
}

or equivalently, by de Morgan's law:

if (dtpDOB.Value >= DateTime.Today.AddYears(-18)
    || dtpDOB.Value <= DateTime.Today.AddYears(-100))
{
    // the date entered was bad, outside permitted range
}

Here I used the "algebraic" fact that

!(x < b && x > a)

is logigally equivalent to

x >= b || x <= a

where the "strict" < reverses and becomes non-strict upon negation.

You should be sure what behavior you want if today is actually the 18th or 100th birthday of the user.

Upvotes: 1

user2466466
user2466466

Reputation: 170

I don't think your if statement will ever be true.

Try using OR rather than AND:

    if (dtpDOB.Value<DateTime.Today.AddYears(-18) || dtpDOB.Value>DateTime.Today.AddYears(-100))
    {
        // show error
    }

Upvotes: 0

Related Questions