Comparing nullable DateTime's in VB.net
I am a c#/asp.net developer and I am 开发者_运维问答having to work on a VB/asp.net. I started out with VB.NET but after years away from it I'm getting confused with the syntax.
I have two variables
Dim originalDate as DateTime?
Dim newDate as DateTime?
Both nullable datetimes, originalDate is a nullable date I am getting from the database and newDate time is set in code, I need to compare them, they can either both have dates, neither have dates or one have and one not.
I have a bit of code as follows:
if origEndDate = origEndDate then
When both origEndDate and origEndDate are "nothing" this statement is false (well when I run it in the watch window it comes back as nothing)!
I don't understand why this is the case because I was under the impression doing an "=" compares the two values and as they are the same surely it should be true?
Can someone explain what I am doing wrong? What syntax should I be using as in C# I can do the above as so:
if (origEndDate == origEndDate) { }
and it will come back as true.
Confused!
Thanks for any help!
Try originalDate.Equals(newDate)
maybe?
(No, this will not cause an NRE when either date is null, since the variables are actually of the value type Nullable(Of DateTime)
and are therefore not actually null until they are boxed.)
use object.equals(originalDate ,newDate )
Using GetValueOrDefault will handle the case when both dates are null
Dim d1 As New Nullable(Of DateTime)
Dim d2 As New Nullable(Of DateTime)
If d1.GetValueOrDefault = d2.GetValueOrDefault Then
{do stuff}
End If
Otherwise, you could check a combination of HasValue to sort out when the dates are undefined.
If (Not d1.HasValue AndAlso Not d1.HasValue) OrElse (d1.HasValue AndAlso d2.HasValue AndAlso d1 = d2) Then
{do stuff}
End If
I found that Date.Equals does work for equality but there arn't any methods for other operators (< or > for example).
If you need to compare for greater or less than you need to use:
If Date1.GetValueOrDefault > Date2.GetValueOrDefault Then
...
End If
I have decided to standardize all my code to use this method for consistency's sake. So now my equality checks have the same format as the example above:
If Date1.GetValueOrDefault = Date2.GetValueOrDefault Then
...
End If
Use Nullable Class methods when you need to know if two Nullables are equal
Dim d1 As New Nullable(Of DateTime)
Dim d2 As New Nullable(Of DateTime)
Dim result As String = "Not Equal"
If( Nullable.Equals(d1,d2))
result = "Equal"
End If
Also you can check greater than, less than
Dim compareResult As Integer
compareResult = Nullable.Compare(d1,d2)
If(compareResult > 0)
result = "d1 greater than d2"
Else If (compareResult < 0)
result = "d1 less than d2"
Else
result = "d1 equal d2"
End If
精彩评论