I have written the following code that tests if the current time is within a time window. It seems to work ok with my test cases, but I would be interested if anyone can see any possible problems or has any ideas for improvements?
Public Function IsCurrentTimeBetween(ByRef dteStartTime As DateTime, ByRef dteEndTime As DateTime) As Boolean
Dim dteStart As DateTime, dteEnd As DateTime, dteCurrent As DateTime
'strip off any date portion of the dates
dteStart = Format(dteStartTime, "HH:mm:ss")
dteEnd = Format(dteEndTime, "HH:mm:ss")
dteCurrent = Format(DateTime.Now, "HH:mm:ss")
If dteEnd < dteStart Then
'the times span midnight
If dteCurrent < dteStart And dteCurrent < dteEnd Then
dteCurrent = dteCurrent.AddDays(1)
End If
dteEnd = dteEnd.AddDays(1)
End If
Return (dteStart <= dteCurrent AndAlso dteCurrent <= dteEnd)
End Function
Usage:
'Work out if we are between 5 to midnight and quarter past midnight
Debug.WriteLine("Is in midnight window? " + IsCurrentTimeBetween("23:55", "00:15").ToString)
