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
I think you’re overcomplicating your code. You could do:
Edit:
If the start and end times are entered by the user, you should first convert the string values into
TimeSpanobjects, then you could use a more flexible method which takes date, min time and max time as parameters:Example usage:
If you have trouble converting string values to TimeSpan you should ask a new question for this specific task.