我的数据库time(7)
和startTime
endTime
个字段
我检索并存储它们:
private TimeSpan? _startTime
private TimeSpan? _endTime
如果_startTime
字段等于10:00:00
且_endTime
等于13:00:00
。如何检查当前时间是否介于两者之间(上午10点和下午1点)?我是否需要以某种方式创建DateTime
?
答案 0 :(得分:1)
这个怎么样?
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;
}
您也可以在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