在VB.net中比较可以为空的DateTime

时间:2010-11-17 16:03:46

标签: c# asp.net vb.net

我是一名c#/ asp.net开发人员,我不得不在VB / asp.net上工作。 我从VB.NET开始,但经过几年的努力,我对语法感到困惑。

我有两个变量

Dim originalDate as DateTime?
Dim newDate as DateTime?

两个可以为空的日期时间,originalDate是我从数据库获取的可以为空的日期,并且newDate时间是在代码中设置的,我需要比较它们,它们可以都有日期,也没有日期或者有一个和一个没有。< / p>

我有一些代码如下:

if origEndDate = origEndDate then

当origEndDate和origEndDate都是“无”时,这个陈述是错误的(当我在监视窗口中运行它时,它会变回无效)!

我不明白为什么会出现这种情况,因为我的印象是“=”比较两个值,因为它们确实相同,它应该是真的吗?

有人可以解释我做错了什么吗?我应该使用什么语法,如在C#中我可以这样做:

if (origEndDate == origEndDate) { }

它会恢复正常。

困惑!

感谢您的帮助!

5 个答案:

答案 0 :(得分:5)

尝试originalDate.Equals(newDate)

(不,当任一日期为空时,这不会导致NRE,因为变量实际上是值类型 Nullable(Of DateTime),因此实际上不是 null,直到它们被装箱。)

答案 1 :(得分:2)

使用object.equals(originalDate,newDate)

答案 2 :(得分:2)

使用GetValueOrDefault将处理两个日期为空的情况

Dim d1 As New Nullable(Of DateTime)
Dim d2 As New Nullable(Of DateTime)
If d1.GetValueOrDefault = d2.GetValueOrDefault Then
  {do stuff}
End If

否则,您可以检查HasValue的组合,以便在未定义日期时进行排序。

If (Not d1.HasValue AndAlso Not d1.HasValue) OrElse (d1.HasValue AndAlso d2.HasValue AndAlso d1 = d2) Then
  {do stuff}
End If

答案 3 :(得分:1)

我发现Date.Equals确实适用于相等但是没有其他运算符的方法(例如&lt;或&gt;)。

如果您需要比较您需要使用的更多或更少:

If Date1.GetValueOrDefault > Date2.GetValueOrDefault Then
    ...
End If

为了保持一致性,我决定将我的所有代码标准化以使用此方法。 所以现在我的等式检查的格式与上面的例子相同:

If Date1.GetValueOrDefault = Date2.GetValueOrDefault Then
    ...
End If

答案 4 :(得分:1)

当您需要知道两个Nullables是否相等时使用Nullable Class methods

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

此外,您可以检查大于,小于

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
相关问题