Reputation: 3978
I have two time(7)
fields in my database startTime
and endTime
I retrieve them and store them:
private TimeSpan? _startTime
private TimeSpan? _endTime
If the _startTime
field was equal to 10:00:00
and _endTime
was equal to 13:00:00
. How can I check if the current time falls between the two (10am and 1pm)? Do I need to create DateTime
with this time somehow?
Upvotes: 0
Views: 46
Reputation: 1990
How about this?
private TimeSpan? _startTime
private TimeSpan? _endTime
public bool IsBetween(DateTime? now = null)
{
if (_startTime == null || _endTime == null)
return false;
if (now == null)
now = DateTime.Now;
TimeSpan currentTime = now.TimeOfDay;
return _startTime <= currentTime && currentTime <= _endTime;
}
You can also just do this in SQL:
CREATE PROCEDURE GetTimes
AS
BEGIN
DECLARE @CurrentTime TIME
SET @CurrentTime = CAST(GETDATE() AS TIME)
SELECT
t.*,
CASE WHEN t.StartTime <= @CurrentTime AND @CurrentTime <= t.EndTime
THEN 1
ELSE 0
END AS 'IsBetween'
FROM
<MyTable> t
END
Upvotes: 1