How can I compare two times in VB.net

微笑、不失礼 提交于 2019-12-01 06:35:35
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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!