VBNet Дата Сравнение - PullRequest
       17

VBNet Дата Сравнение

0 голосов
/ 05 января 2012

В настоящее время у меня есть этот код.

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

Есть ли какая-либо замена в приведенном выше коде? Так же, как BETWEEN в SQL-запросах?

Ответы [ 3 ]

6 голосов
/ 05 января 2012

Нет ничего встроенного, но вы можете использовать метод расширения:

<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."))
2 голосов
/ 05 января 2012

Нет, в .NET нет оператора МЕЖДУ, вы действительно его упускаете?

Примечание :

Вы можете / должны использовать вместо этого IFиз IIF .

Dim message = _
    If((iCurrentDate > iStartDate) AndAlso (iCurrentDate < iEndDate), _
    "Current date is within the range.", _
    "Current date is not in the range.")
  • Это быстрее: вторая часть будет оцениваться, только если first * false, без бокса / распаковки
  • Это безопаснее: нет NullRefernceException, потому чтоВы забыли выше
  • Это более читабельно и безопасно для типов
1 голос
/ 05 января 2012

Прямой замены нет. Я видел что-то подобное в случае выбора:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...