获取两个DateTime之间的(平铺)小时列表

时间:2012-04-17 19:08:31

标签: c#

我写了一个函数来包含给我一个介于两个DateTime之间的小时列表。

但最后它看起来并不是很容易阅读,它让我想要对它进行单元测试,即使我正在进行的项目根本不进行单元测试。

所以我的问题是,是否有更清晰,更有效的方式来写这个?:

代码:

private List<DateTime> GetHoursForEvent(DateTime start, DateTime end)
{
    var hours = new List<DateTime>();

    DateTime startFloor = Convert.ToDateTime(start.ToString("MM/dd/yyyy HH:00:00"));
    DateTime endFloor = Convert.ToDateTime(end.ToString("MM/dd/yyyy HH:00:00"));

    for (double dblDate = startFloor.ToOADate(); 
         dblDate <= endFloor.ToOADate(); 
         dblDate += (1.0 / 24.0))
    {
        hours.Add(DateTime.FromOADate(dblDate));
    }

    return hours;
}

输入:

DateTime start = Convert.ToDateTime("2012-04-01 04:22:00");
DateTime end   = Convert.ToDateTime("2012-04-02 00:05:00");

结果:

2012-04-01 04:00:00
2012-04-01 05:00:00
2012-04-01 06:00:00
2012-04-01 07:00:00
2012-04-01 08:00:00
2012-04-01 09:00:00
2012-04-01 10:00:00
2012-04-01 11:00:00
2012-04-01 12:00:00
2012-04-01 13:00:00
2012-04-01 14:00:00
2012-04-01 15:00:00
2012-04-01 16:00:00
2012-04-01 17:00:00
2012-04-01 18:00:00
2012-04-01 19:00:00
2012-04-01 20:00:00
2012-04-01 21:00:00
2012-04-01 22:00:00
2012-04-01 23:00:00
2012-04-02 00:00:00

我感觉我正在重新发明轮子。

2 个答案:

答案 0 :(得分:9)

是的,这样的事情对你来说应该更好:

private List<DateTime> GetHoursForEvent(DateTime start, DateTime end)
{
    var hours = new List<DateTime>();
    var current = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0);
    while(current <= end)
    {
        hours.Add(current);
        current = current.AddHours(1);
    }
    return hours;
}

您甚至可能希望将其转换为流媒体方式,除非您需要返回List的特定原因:

private IEnumerable<DateTime> GetHoursForEvent(DateTime start, DateTime end)
{
    var current = new DateTime(start.Year, start.Month, start.Day, start.Hour, 0, 0);
    while(current <= end)
    {
        yield return current;
        current = current.AddHours(1);
    }
}

答案 1 :(得分:1)

尝试使用此代码

private List<DateTime> GetHoursForEvent(DateTime start, DateTime end)
    {
        List<DateTime> hours = new List<DateTime>();
        while (start < end)
        {
            hours.Add(start);
            start = start.AddHours(1);
        }
        return hours;
    }