user1296417 user1296417 - 3 months ago 20
Vb.net Question

How to check time range

I implmented a function to check time range in vb.net. But it is giving me wrong output.
My starttime is everyday at 11.00 Pm and end Time is 5.00 AM. My function if i pass 1.10 AM does not return me true output as this falls under that time range. Not sure what iam doing wrong.

Private Function CheckTimeRange() As Boolean
Dim retValue As Boolean = True
Try
Dim Dt As DateTime = DateTime.Now
Dim StartDt As DateTime = Convert.ToDateTime("11.00 PM")
Dim EndDt As DateTime = Convert.ToDateTime("5.00 AM")

Dim startTime As New TimeSpan(StartDt.Hour, StartDt.Minute, 0)
Dim endTime As New TimeSpan(EndDt.Hour, EndDt.Minute, 0)
Dim now As TimeSpan = DateTime.Now.TimeOfDay

If (now > startTime) AndAlso (now < endTime) Then
retValue = True
Else
retValue = False
End If
Return retValue
Catch ex As Exception
End Try
End Function

Answer

I think you're overcomplicating your code. You could do:

Private Function CheckTimeRange() As Boolean
    Return DateTime.Now.Hour >= 23 OrElse DateTime.Now.Hour < 5
End Function

Edit:

If the start and end times are entered by the user, you should first convert the string values into TimeSpan objects, then you could use a more flexible method which takes date, min time and max time as parameters:

Private Function CheckTimeRange(myDate As DateTime, minTime as TimeSpan, maxTime As TimeSpan) As Boolean
    If minTime > maxTime Then
        Return myDate.TimeOfDay >= minTime OrElse myDate.TimeOfDay < maxTime
    Else
        Return myDate.TimeOfDay >= minTime AndAlso myDate.TimeOfDay < maxTime
    End If
End Function

Example usage:

Dim minTime As New TimeSpan(23, 0, 0) 'Should be converted from 11.00 PM
Dim maxTime As New TimeSpan(5, 0, 0) 'Should be converted from 5.00 AM
CheckTimeRange(New Date(2012, 1, 1, 15, 0, 0), minTime, maxTime) '==> false
CheckTimeRange(New Date(2012, 1, 1, 22, 30, 0), minTime, maxTime) '==> false
CheckTimeRange(New Date(2012, 1, 1, 23, 00, 0), minTime, maxTime) '==> true
CheckTimeRange(New Date(2012, 1, 2, 1, 10, 0), minTime, maxTime) '==> true
CheckTimeRange(New Date(2012, 1, 2, 4, 59, 0), minTime, maxTime) '==> true
CheckTimeRange(New Date(2012, 1, 2, 5, 10, 0), minTime, maxTime) '==> false

If you have trouble converting string values to TimeSpan you should ask a new question for this specific task.