I want to compare two times in VB.net:
I have 1:42:21 PM and I want it to compare with TimeOfDay in VB.net how can I do that?
New DateTime(1, 1, 1, 13, 42, 21) > TimeOfDay
Or you can enclose a DateTime
expression in #
signs:
TimeOfDay > #1:42:21 PM#
Show the time difference in hours, minutes and seconds
Dim TimeEnd As DateTime = #5:00:00 PM#
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim span As System.TimeSpan = TimeEnd.TimeOfDay - DateTime.Now.TimeOfDay
Label1.Text = span.Hours & "hr:" & span.Minutes & "min:" & span.Seconds & "sec"
End Sub
You'd work out the format of your input time, and then call the ToString() method on your vb.net object, putting the same format in.
So for example, if your input format is h:mm:ss tt as it appears to be in your case, one method would be to do:
Dim compareTime As String = "1:42:21 PM"
If compareTime = DateTime.Now.ToString("h:mm:ss tt") Then
' The times match
End If
If you want to do some kind of comparison, you should use the DateTime.Parse() function to convert your input date into a DateTime object. Then you can simply use the > or < signs:
Dim myCompareTime As DateTime = DateTime.Parse("1:42:21 PM")
If myCompareTime.TimeOfDay > DateTime.Now.TimeOfDay Then
' Compare date is in the future!
End If
The following sample function can be used to compare time
Function comTime()
Dim t1 As Integer = DateTime.Now.TimeOfDay.Milliseconds
Dim t2 As Integer = DateTime.Now.AddHours(1).Millisecond
If (t1 > t2) Then
MessageBox.Show("t1>t2")
ElseIf (t1 = t2) Then
MessageBox.Show("t1=t2")
Else
MessageBox.Show("t2>t1")
End If
End Function
is it something along the lines of this that you are looking for?
To compare the time portion of two DateTime values:
Dim TimeStart as DateTime = #1:42:21 PM#
Dim TimeEnd as DateTime = #2:00:00 PM#
If TimeStart.TimeOfDay < TimeEnd.TimeOfDay Then
Console.WriteLine("TimeStart is before TimeEnd")
End If
来源:https://stackoverflow.com/questions/2603182/how-can-i-compare-two-times-in-vb-net