按DateTime对象列表中的时间范围过滤

时间:2014-11-21 23:03:24

标签: c# datetime time

我有一个DateTime对象列表。

我需要从这个列表中仅获取时间部分为'00:00:01'和'12:00:00'之间的对象。

如何查询此列表?

如果我要进行SQL查询,我会这样做

SELECT TspCreated,
    CASE 
        WHEN cast(TspCreated as time) > '00:00:00' AND 
             cast(TspCreated as time) <= '12:00:00' 
             THEN '00 - 12'
        WHEN cast(TspCreated as time) > '12:00:00' AND 
             cast(TspCreated as time) <= '18:00:00' 
             THEN '12 - 18'
        WHEN cast(TspCreated as time) > '18:00:00' AND 
             cast(TspCreated as time) <= '23:59:59' 
             THEN '18 - 24'
    END AS TimeFrame
FROM MyTable

编辑:

感谢Jon Skeet answer我有办法使用Timespan对象作为查询的边界。不幸的是,在我的情况下,答案不适用,因为Linq-to-Entities不支持使用TimeOfDay属性。我最终使用了Entity Framework Canonical Functions

TimeSpan ts_0 = new TimeSpan( 0, 0, 0 );
TimeSpan ts_12 = new TimeSpan( 12, 0, 0 );
int NumOfIssues = ctx.MyEntitySet.Where( x => 
                      DbFunctions.CreateTime( x.TspUsed.Hour, x.TspUsed.Minute, x.TspUsed.Second ) >= ts_0 &&
                      DbFunctions.CreateTime( x.TspUsed.Hour, x.TspUsed.Minute, x.TspUsed.Second ) < ts_12).Count();

1 个答案:

答案 0 :(得分:1)

在我看来,你所需要的只是DateTime.TimeOfDay属性。如果你能够,我会建议稍微改变你的条件,以便下限是包含,上限是独占,例如。

var time = dateTime.TimeOfDay;
if (time.Hours < 12)
{
    Console.WriteLine("Morning");
}
else if (time.Hours < 18)
{
    Console.WriteLine("Afternoon");
}
else
{
    Console.WriteLine("Evening");
}

作为一个方便的例子,你当前的分类完全不包括午夜时间以及晚上11:59:59到午夜之间的任何事情。 11:59:59.999

或者您可以为边界创建适当的TimeSpan值,并使用常规<<=等运算符。例如:

TimeSpan noon = new TimeSpan(12, 0, 0);
TimeSpan sixPm = new TimeSpan(18, 0, 0);
TimeSpan time = dateTime.TimeOfDay;
if (time < noon)
{
    ...
}
else if (time < sixPm)
{
    ...
}
else
{
    ...
}

请注意,对于这两种方法,我只会检查每个if语句中的一个条件,因为我基本上从午夜开始一整天。如果您只想检查中间的一个乐队,您可以说:

if (noon <= time && time < sixPm)

稍微偏离一点,我从未喜欢TimeOfDay返回TimeSpan - 经过的一段时间与一天中的时间不一样。如果您有同样的想法并且您正在进行大量的日期/时间工作,您可能需要考虑查看我的Noda Time项目,该项目有批次更多类型来表示各种日期和时间的各个方面。

相关问题