将日期时间范围拆分为小时数

时间:2017-07-26 11:39:04

标签: c#

我有一个课程,提供从knitted_obj开始到Begin结束的时间范围(句点):

End

让我们说public class Period { public DateTime Begin { get; set; } public DateTime End { get; set; } } = Begin01/07/2017 7:50:00 = End

我需要得到的是一组来自基础的更详细01/07/2017 12:30:00对象,它们包含每小时分割的时期 - 示例的输出应该是这样的(日期部分被省略):

[0] Period

[1] Begin = 7:50:00, End = 7:59:59

[2] Begin = 8:00:00, End = 8:59:59

[3] Begin = 9:00:00, End = 9:59:59

[4] Begin = 10:00:00, End = 10:59:59

[5] Begin = 11:00:00, End = 11:59:59

进行拆分的最佳方法是什么?

3 个答案:

答案 0 :(得分:3)

Period period = new Period();
period.Begin = new DateTime(2017, 7,1, 7,50,0);
period.End = new DateTime(2017, 7, 1, 12, 30, 0);

DateTime start = period.Begin;

List<Period> periods = new List<Period>();
while(start < period.End)
{
   DateTime end = start;
   end = end.AddMinutes(-end.Minute);
   end = end.AddSeconds(-1);
   end = end.AddHours(1);
   if(end > period.End)
      end = period.End;

   periods.Add(new Period{Begin = start, End = end});
   start = end.AddSeconds(1);
}

foreach(var p in periods)
{
   Console.WriteLine($"Start: {p.Begin.ToLongTimeString()} End: 
   {p.End.ToLongTimeString()}");
}

这导致

Start: 07:50:00 End: 07:59:59
Start: 08:00:00 End: 08:59:59
Start: 09:00:00 End: 09:59:59
Start: 10:00:00 End: 10:59:59
Start: 11:00:00 End: 11:59:59
Start: 12:00:00 End: 12:30:00

答案 1 :(得分:3)

您可以编写一个简单的方法,将start和end作为DateTime对象并返回句点集合。

static IEnumerable<Period> GetPeriods (DateTime start, DateTime end)
{
    // Create a DateTime as a pointer to increment
    DateTime ptr = start;
    while (ptr < end)
    {
        // Return a new Period, starting with the current pointer time and ending with
        //   the pointer time plus 00:59:59 (59 * 60 + 59 = 3599s)
        yield return new Period() { Start = ptr, End = ptr.AddSeconds(3599) };

        // Increment the pointer
        ptr = ptr.AddHours(1);
    }
}

答案 2 :(得分:1)

试试这个solution

var periods = new List<Period>();
var period = new Period 
{ 
    Begin = new DateTime(2017, 07, 01, 7, 50, 0), 
    End = new DateTime(2017, 07, 01, 12, 30, 0) 
};        
var previous = period.Begin;

do
{
    var next = new Period 
    { 
        End = previous.AddSeconds(3600 - previous.Minute * 60 - 1), 
        Begin = previous 
    };
    previous = next.End.AddSeconds(1);
    if (next.End < period.End.AddSeconds(-1))
        periods.Add(next);
    else
    {
        next.End = period.End.AddSeconds(-1);
        periods.Add(next);
        break;
    }                
} while (true);

<强>结果:

7/1/2017 7:50:00 AM - 7/1/2017 7:59:59 AM
7/1/2017 8:00:00 AM - 7/1/2017 8:59:59 AM
7/1/2017 9:00:00 AM - 7/1/2017 9:59:59 AM
7/1/2017 10:00:00 AM - 7/1/2017 10:59:59 AM
7/1/2017 11:00:00 AM - 7/1/2017 11:59:59 AM
7/1/2017 12:00:00 PM - 7/1/2017 12:29:59 PM