TimeRange
—
A range of Time type
Problem
The Problem!
Solution
The Solution!
Discussion
The Discussion!
Example
Sample showing checking to see if a point in time is contained within a specific range.
Dim jobStreamRange As New TimeRange(#11:00:00 PM#, #2:00:00 AM#)
Dim actionTime As DateTime = #8/11/2004 11:03:00 PM#
If jobStreamRange.Contains(actionTime) Then
End If
Sample showing how to find out shift shift a person clocked in during.
Dim firstShift As New TimeRange(#8:00:00 AM#, #4:00:00 PM#)
Dim secondShift As New TimeRange(#4:00:00 PM#, #12:00:00 AM#)
Dim thirdShift As New TimeRange(#12:00:00 AM#, #8:00:00 AM#)
Dim clockIn As DateTime
If firstShift.Contains(clockIn) Then
ElseIf secondShift.Contains(clockIn) Then
ElseIf thirdShift.Contains(clockIn) Then
Else
Throw New ArgumentException("clockIn", clockIn, "Clock is not in any shifts")
End If
Source
Define the time range type.
Option Strict On
Option Explicit On
Public Structure TimeRange
Public Shared ReadOnly Empty As TimeRange
Private ReadOnly m_start As TimeSpan
Private ReadOnly m_finish As TimeSpan
Private ReadOnly m_midnight As Boolean
Public Sub New(ByVal start As DateTime, ByVal finish As DateTime)
MyClass.New(start.TimeOfDay, finish.TimeOfDay)
End Sub
Public Sub New(ByVal start As TimeSpan, ByVal finish As TimeSpan)
m_start = start
m_finish = finish
m_midnight = (TimeSpan.Compare(m_start, m_finish) > 0)
End Sub
Public ReadOnly Property Start() As TimeSpan
Get
Return m_start
End Get
End Property
Public ReadOnly Property Finish() As TimeSpan
Get
Return m_finish
End Get
End Property
Public Function Contains(ByVal value As DateTime) As Boolean
Dim timeOfDay As TimeSpan = value.TimeOfDay
If m_midnight Then
Return TimeSpan.Compare(m_start, timeOfDay) <= 0 OrElse TimeSpan.Compare(timeOfDay, m_finish) <= 0
Else
Return TimeSpan.Compare(m_start, timeOfDay) <= 0 AndAlso TimeSpan.Compare(timeOfDay, m_finish) <= 0
End If
End Function
Public Overrides Function ToString() As String
Return m_start.ToString() & " " & m_finish.ToString()
End Function
Public Shared Function Parse(ByVal s As String) As TimeRange
s = s.Trim()
Dim index As Integer
index = s.IndexOf(" "c)
Dim start As String = s.Substring(0, index - 1)
Dim finish As String = s.Substring(index + 1).Trim()
Dim startTime As TimeSpan = TimeSpan.Parse(start)
Dim finishTime As TimeSpan = TimeSpan.Parse(finish)
Return New TimeRange(startTime, finishTime)
End Function
End Structure
See Also