如何将字符串变量与日期变量进行比较

时间:2014-07-17 06:51:55

标签: vb.net datetime string-comparison

   Dim strLastDate as string ' fill this value from database field 
   Dim TodayDate as Date = Format(Now.Date, "dd/MM/yyyy")
  • 这里

    strLastDate = "16/07/2014 04:39:10"

    TodayDate =17/07/2014"

  • 如何比较这些日期?根据结果​​,我必须显示警告。

1 个答案:

答案 0 :(得分:2)

 Private Sub CompareDates(ByVal strLastDate As String)
    'as you said strLastDate is getting from database 
    'lets assume strLastDate = "16/07/2014 04:39:10"
    Dim dteToday As Date = CDate(Format(Now.Date, "dd/MM/yyyy"))
    Dim dateDiffer As Integer
    Dim dteLastdate As Date
    'formats the strLastDate like "dd/MM/yyyy"
    strLastDate = strLastDate.Substring(0, 10) 'you'll get 16/07/2014
    'converts string to date 
    dteLastdate = CDate(strLastDate)
    'now Compare  dteToday with dteLastdate
    dateDiffer = dteToday.Subtract(dteLastdate).TotalDays
    If dateDiffer > 2 Then
        'your alert message is here
    End If
End Sub