簡體   English   中英

在VB.net中比較可以為空的DateTime

[英]Comparing nullable DateTime's in VB.net

我是ac#/ asp.net開發人員,我不得不在VB / asp.net上工作。 我從VB.NET開始,但經過幾年的努力,我對語法感到困惑。

我有兩個變量

Dim originalDate as DateTime?
Dim newDate as DateTime?

兩個可以為空的日期時間,originalDate是我從數據庫獲取的可以為空的日期,newDate時間是在代碼中設置的,我需要比較它們,它們既可以有日期,也可以有一個日期,也可以有一個日期。

我有一些代碼如下:

if origEndDate = origEndDate then

如果origEndDate和origEndDate都是“無”,那么這個語句就是假的(當我在監視窗口中運行它時,它就會變回來)!

我不明白為什么會出現這種情況,因為我的印象是“=”比較兩個值,因為它們是相同的,它應該是真的嗎?

誰能解釋我做錯了什么? 我應該使用什么語法,如在C#中我可以這樣做:

if (origEndDate == origEndDate) { }

它會像真的一樣回歸。

困惑!

謝謝你的幫助!

試試originalDate.Equals(newDate)吧?

(不,當任一日期為空時,這不會導致NRE,因為變量實際上是值類型 Nullable(Of DateTime) ,因此在裝箱之前它們實際上不為空。)

使用object.equals(originalDate,newDate)

當兩個日期都為空時,使用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

當您需要知道兩個Nullables是否相等時,請使用Nullable Class方法

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

我發現Date.Equals確實可以用於相等但是沒有其他運算符的任何方法(例如<或>)。

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

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

為了保持一致性,我決定將我的所有代碼標准化以使用此方法。 所以現在我的等式檢查具有與上面示例相同的格式:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM