我在VB.net中有1个字符串
Dim str As String = "2014/08/15 19:45"
我有2次
Dim startDate As String = "6:30"
Dim endDate As String = "22:00"
如何比较“str”和“startDate”& “endDate”?
答案 0 :(得分:4)
首先,您有字符串而不是DateTimes或TimeSpan。但如果你想比较它们,你需要两者。因此,请使用Date.Parse
,Date.ParseExact
(或...TryParse
版本来检查无效数据):
Dim str As String = "2014/08/15 19:45"
Dim dt1 = Date.ParseExact(str, "yyyy/MM/dd HH:mm", CultureInfo.InvariantCulture)
Dim startDate As String = "6:30"
Dim tsStart = TimeSpan.Parse(startDate)
Dim endDate As String = "22:00"
Dim tsEnd = TimeSpan.Parse(endDate)
现在你可以比较它们了:
If dt1.TimeOfDay >= tsStart AndAlso dt1.TimeOfDay <= tsEnd Then
' Yes, 19:45 is between 6:30 and 22:00 '
End If
答案 1 :(得分:0)
首先,您应该使用日期来存储值。然后检查时间组件就是一件简单的事情。请注意,下面的实现是包含的(即如果时间恰好是开始或结束时间,它将打印消息。
Dim dateToCheck As Date = Date.Parse("2014/08/15 19:45")
' The date portion doesn't matter, so I'm just using 1/1/1970.
Dim startTimeDate As Date = New Date(1970, 1, 1, 6, 30, 0)
Dim endTimeDate As Date = New Date(1970, 1, 1, 22, 0, 0)
Dim afterOrEqualToStartTime As Boolean = (dateToCheck.Hour >= startTimeDate.Hour) And (dateToCheck.Minute >= startTimeDate.Minute) And (dateToCheck.Second >= startTimeDate.Second)
Dim beforeOrEqualToEndTime As Boolean = (dateToCheck.Hour <= endTimeDate.Hour) And (dateToCheck.Minute <= endTimeDate.Minute) And (dateToCheck.Second <= endTimeDate.Second)
If (afterOrEqualToStartTime And beforeOrEqualToEndTime) Then
MsgBox("Date is between the start and end times")
End If
答案 2 :(得分:0)
Dim str As String = "2014/08/15 19:45"
Dim time As DateTime = DateTime.Parse(str)
'here get the hour and minutes, and now you can compare with the others
Dim tmpTime As DateTime = time.ToString("t")
答案 3 :(得分:0)
使用日期变量比较时间很困难。
使用容差的数据差异是处理二进制时间的一种方法。
我使用字符串:
Dim dt As Date = "2014/08/15 22:45"
Dim s As String = dt.ToString("H:MM")
If s > "06:30" And s <= "22:00" Then
MsgBox("yes")
Else
MsgBox("no")
End If
注意样本中06:30的前导0。