VBNet日期比较

时间:2012-01-05 14:34:02

标签: vb.net date compare

目前,我有这段代码。

Dim iCurrentDate As Date = Now
Dim iStartDate As Date = CDate(dtFrom.Text)
Dim iEndDate As Date = CDate(dtTo.Text)

If (iCurrentDate > iStartDate) And (iCurrentDate < iEndDate) Then
    Console.WriteLine("Current date is within the range.")
    'Other Codes here
Else
    Console.WriteLine("Current date is in the range.")
    'Other Codes here
End If

OR

Dim iObj As Object = IIf((iCurrentDate > iStartDate) And (iCurrentDate < iEndDate), "Current date is within the range.", "Current date is in the range.")
Console.WriteLine(iObj.ToString)
'Other Codes here

上面的代码有替代品吗?就像在SQL查询中的BETWEEN一样?

3 个答案:

答案 0 :(得分:6)

内置任何内容,但您可以使用扩展方法:

<Extension()> _
Public Function IsBetween(theDate As DateTime, minDate As DateTime, maxDate As DateTime) As Boolean
    Return theDate > minDate AndAlso theDate < maxDate
End Function

然后你可以像这样使用它:

If iCurrentDate.IsBetween(iStartDate, iEndDate) Then
    Console.WriteLine("Current date is within the range.")
    'Other Codes here
Else
    Console.WriteLine("Current date is not in the range.")
    'Other Codes here
End If

或者像这样:

Console.WriteLine(If(iCurrentDate.IsBetween(iStartDate, iEndDate), _
                     "Current date is within the range.", _
                     "Current date is not in the range."))

答案 1 :(得分:2)

不,.NET中没有BETWEEN运算符,你真的错过了吗?

注意

你可以/ use IF instead of IIF

Dim message = _
    If((iCurrentDate > iStartDate) AndAlso (iCurrentDate < iEndDate), _
    "Current date is within the range.", _
    "Current date is not in the range.")
  • 速度更快:第一部分仅在第一部分false评估时才会被评估,没有装箱/拆箱
  • 它更安全:没有NullRefernceException,因为你已经忘记了上面
  • 它更具可读性和类型安全性

答案 2 :(得分:1)

没有直接的替代品,我已经看到了一些选择案例:

Select Case iCurrentDate
    Case iStartDate To iEndDate
        'is between
    Case Else
        'is not
End Select

我从未使用过类似的东西。我不确定它的起源是什么。我通常会使用AndAlso对代码进行一些修改:

   If (iCurrentDate > iStartDate) AndAlso (iCurrentDate < iEndDate) Then
            Console.WriteLine("Current date is within the range.")
            'Other Codes here
        Else
            Console.WriteLine("Current date is in the range.")
            'Other Codes here
        End If