patterncsharpMinor
Function to test if the current time is within a time window
Viewed 0 times
thefunctiontimewithintestcurrentwindow
Problem
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?
Usage:
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 FunctionUsage:
'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)Solution
You are taking a DateTime, formatting it to a string, then assigning that to another datetime, just to get the time of day. That won't compile with Option Strict On. What you want is provided by DateTime.TimeOfDay.
I would also change ByRef to ByVal in the parameter list.
Once you are comparing timespan instead of date, you don't have to do date addition. You can just detect the wrap-around case and you only have to check endTime.
I would also change ByRef to ByVal in the parameter list.
Once you are comparing timespan instead of date, you don't have to do date addition. You can just detect the wrap-around case and you only have to check endTime.
Public Function IsCurrentTimeBetween(ByVal dteStartTime As DateTime, ByVal dteEndTime As DateTime) As Boolean
Dim startTime, endTime, currentTime As TimeSpan
startTime = dteStartTime.TimeOfDay
endTime = dteEndTime.TimeOfDay
currentTime = Now.TimeOfDay
If endTime < startTime Then
'the times span midnight
Return (currentTime <= endTime)
Else
'the times do not span midnight
Return (startTime <= currentTime AndAlso currentTime <= endTime)
End If
End FunctionCode Snippets
Public Function IsCurrentTimeBetween(ByVal dteStartTime As DateTime, ByVal dteEndTime As DateTime) As Boolean
Dim startTime, endTime, currentTime As TimeSpan
startTime = dteStartTime.TimeOfDay
endTime = dteEndTime.TimeOfDay
currentTime = Now.TimeOfDay
If endTime < startTime Then
'the times span midnight
Return (currentTime <= endTime)
Else
'the times do not span midnight
Return (startTime <= currentTime AndAlso currentTime <= endTime)
End If
End FunctionContext
StackExchange Code Review Q#2460, answer score: 5
Revisions (0)
No revisions yet.