Christian EA Christian EA - 21 days ago 11
Vb.net Question

Time comparison in VB.NET

I'm trying to see if the current time is between two times, but I've been having trouble with this one:

This is my code:

If DATE.NOW < CDate(#6:30:00 AM#) And DATE.NOW >= CDate(#10:30:00 PM#) Then
SHIFT = "NIGHT"
End If


If my time is 11:15 pm I expect to be between the range above, but it doesn't.

More than the formula to get this, I would like to know how the time works in VB.NET when you are comparing am vs. pm.

Answer Source

You've got to change the condition to OrElse due to that internally dates are just regular numbers (in this case dates are represented by how many microseconds have lapsed since 0001-01-01). Therefore Date.Now cannot possibly be both less than 6:30 AM and more or equal to 10:30 PM.

You've also got to add .TimeOfDay to both sides as doing so will compare only the time of the day, ignoring the date. #6:30:00 AM# will evaluate to 0001-01-01 6:30:00 AM, which is always less than Date.Now (2017-09-25 xx:xx:xx).

This should work:

If Date.Now.TimeOfDay < #6:30:00 AM#.TimeOfDay OrElse Date.Now.TimeOfDay >= #10:30:00 PM#.TimeOfDay Then

This checks if the time is less than 6:30 AM, or more or equal to 10:30 PM.