我觉得 Larstech 的答案是最好的(假设您DateTime
最初使用的是 a ,而不仅仅是月份和日期的整数,或者还有其他获取年份的方法)。
我发布了一个答案来解释为什么你的代码没有按照你期望的方式工作。您的代码给您带来问题的原因是您的条件测试Month
不正确并且将始终返回 true,这意味着您的内部 IF 语句将执行。
If Month = 4 Or 6 Or 9 Or 11 Then
6, 9, and 11 will all evaluate to true, making the whole if check true (I believe any non-zero integer value will evaluate to true in VB.NET, but haven't been able to dig up a link to substantiate it. Testing on my machine in VS 2012 supports that, as well as some other discussions I've seen, however).
So what is happening is that the last if block (as you have it written) for the month will always evaluate to True
, and as long as the day is 1 to 31 dateOkay
will evaluate to true, no matter what the actual month is.
What you should do is this:
If Month = 4 Or Month = 6 Or Month = 9 Or Month = 11 Then
This will evaluate as you expect it to, and the rest or your code will work as expected.
I would recommend using OrElse
instead of Or
, which will enable you to perform short-circuit evaluation similar to the AndAlso
you used. In other words, as soon as one of the conditional tests in the if statement using OrElse
evaluates to true, the rest of the conditional tests will be ignored. AndAlso
will not evaluate any additional conditional tests once it encounters a False result.
In comparison, And
and Or
will evaluate all the tests, regardless of outcome. For example, If Month = 1 Or Month = 3 Or Month = 4 Then
will run each of the individual tests, even if Month
is 1.
Finally, if you're not setting dateOkay
before evaluating the date, I would set it explicitly to False before the evaluation. Putting it altogether you'd get something like this:
dateOkay = False
If Month = 4 OrElse Month = 6 OrElse Month = 9 OrElse Month = 11 Then
If (1 <= Day) AndAlso (Day <= 30) Then
DateOkay= True
End If
End If
If Month = 2 Then
If (1 <= Day) AndAlso (Day <= 28) Then
DateOkay = True
End If
End If
If Month = 1 OrElse Month = 3 OrElse Month = 5 OrElse Month = 7 OrElse Month = 8 OrElse Month = 10 OrElse Month = 12 Then
If (1 <= Day) AndAlso (Day <= 31) Then
DateOkay = True
End If
End If
Again, however, Larstech's answer is the best to your question " Is there a simpler way of doing this?".