0

How can I compare two diferent Time object in VB.Net. I have implemented the following snippet. I am still unable to get the desired output.

time_One = Now
el_Time = time_One - time_Two
Label1.Text = Now.ToShortTimeString
If Label1.Text < "06:30:00 PM" Then
Label1.Text = "-----"
Else
Label1.Text = el_Time.ToString
End If

Test Case:

I want to compare the current time with "06:30:00 PM".

If the current time is smaller than "06:30:00 PM" then, perform an action

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
Jing Jie
  • 41
  • 5

3 Answers3

1

Declare time_One, time_Two and el_Time as date datatype.

Then do the time comparison as:

 time_One = Now
 el_Time = New Date(DateDiff(DateInterval.Second, time_One, time_Two)

 If DateDiff(DateInterval.Second, TimeValue(Label1.Text), TimeValue("06:30 PM")) < 0 Then
    Label1.Text = "-----"
 Else
    Label1.Text = el_Time.ToString
 End If
Veera
  • 3,412
  • 2
  • 14
  • 27
1

You can try this simple way:

Dim dtNow As Date = Date.Now()
Dim myDate As Date = New Date(dtNow.Year, dtNow.Month, dtNow.Day, 6, 30, 0)

If myDate < dtNow Then
    ' Perform an action
End If

It uses the Date constructor to create a new DateTime with the same day as today and the desired time, to compare it with the actual time and date. Then uses the comparing operator given by Date type.

SysDragon
  • 9,692
  • 15
  • 60
  • 89
0

You could use TimeSpan. Take a look at this:

Dim dtLimit As New TimeSpan(6, 30, 0)
Dim iMinutes As Double = (Date.Now.TimeOfDay - dtLimit).TotalMinutes 

If iMinutes < 0 Then 
    ' Perform an action
End If

This code calculates the difference between two given moments (only time, without date); the present one and the desired one.

SysDragon
  • 9,692
  • 15
  • 60
  • 89