当存储在MSSQL中时,如何检查时间字段是否在C#中的当前时间之间

时间:2016-09-05 05:55:07

标签: c# .net sql-server

我的数据库time(7)startTime

中有两个endTime个字段

我检索并存储它们:

private TimeSpan? _startTime
private TimeSpan? _endTime

如果_startTime字段等于10:00:00_endTime等于13:00:00。如何检查当前时间是否介于两者之间(上午10点和下午1点)?我是否需要以某种方式创建DateTime

1 个答案:

答案 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