user1761176
user1761176

Reputation: 103

How to compare two time in vb.net

I have 1 String in VB.net

Dim str As String = "2014/08/15 19:45"

I have 2 time

Dim startDate As String = "6:30"
Dim endDate As String = "22:00"

How to compare "str" with "startDate" & "endDate" ?

Upvotes: 0

Views: 12530

Answers (4)

rheitzman
rheitzman

Reputation: 2297

Comparing time is difficult using Date variables.

Using a data difference, with a tolerance, is one way to deal with binary time.

I use strings:

    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

note the leading 0 in 06:30 in the sample.

Upvotes: 0

patovega
patovega

Reputation: 343

 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")

Upvotes: 0

wottle
wottle

Reputation: 13619

First, you should be using dates to store the values. Then it's a simple matter of checking the time components. Note that the implementation below is inclusive (i.e. if the time is exactly the start or end time, it will print the message.

    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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460028

First, you have strings not DateTimes or TimeSpan. But you need both if you want to compare them. So use Date.Parse, Date.ParseExact (or the ...TryParse versions to check invalid data):

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)

Now you can compare them:

If dt1.TimeOfDay >= tsStart AndAlso dt1.TimeOfDay <= tsEnd Then
 ' Yes, 19:45 is between  6:30 and 22:00 '
End If

Upvotes: 4

Related Questions