How can I compare two times in VB.net

2019-02-18 00:01发布

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?

5条回答
叛逆
2楼-- · 2019-02-18 00:12
New DateTime(1, 1, 1, 13, 42, 21) > TimeOfDay

Or you can enclose a DateTime expression in # signs:

TimeOfDay > #1:42:21 PM#
查看更多
forever°为你锁心
3楼-- · 2019-02-18 00:12

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
查看更多
Emotional °昔
4楼-- · 2019-02-18 00:22
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?

查看更多
做个烂人
5楼-- · 2019-02-18 00:27

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
查看更多
小情绪 Triste *
6楼-- · 2019-02-18 00:32

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
查看更多
登录 后发表回答