C#迭代日期和时间的集合并生成缺少的日期和时间

时间:2014-10-04 09:40:30

标签: c#

我在迭代和抽样日期和时间的集合中遇到了一些问题。我需要的是按分钟生成缺少的日期时间。以下数据只是一小部分,我的数据包含超过5000行:

DateTime[] times = new DateTime[6];
times[0] = new DateTime(2014, 09, 1, 11, 54, 40);
times[1] = new DateTime(2014, 09, 1, 11, 55, 40);
times[2] = new DateTime(2014, 09, 1, 11, 57, 40); // Minute 57
times[3] = new DateTime(2014, 09, 1, 12, 00, 40); // Minute 00 but next hour
times[4] = new DateTime(2014, 09, 1, 12, 01, 40);
times[5] = new DateTime(2014, 09, 1, 12, 12, 40);

for (int i = 0; i < times.Length- 1; i++)
{
    DateTime currentTime = times[i].AddMinutes(1);
    DateTime nextTime = times[i + 1];
    int diff = nextTime.Minute - currentTime.Minute;

    if (diff == 0)
    {
        // Next time is not a missed one.
        Console.WriteLine(times[i]);
        Console.WriteLine(times[i + 1]);
    }
    else 
    { 
        while(currentTime < nextTime)
        {
            // Generate missed date and time.
            currentTime = currentTime.AddMinutes(1);
            Console.WriteLine(currentTime);
        }
    }
}

结果: enter image description here

希望: enter image description here

2 个答案:

答案 0 :(得分:1)

DateTime[] times = new DateTime[6];
times[0] = new DateTime(2014, 09, 1, 11, 54, 40);
times[1] = new DateTime(2014, 09, 1, 11, 55, 40);
times[2] = new DateTime(2014, 09, 1, 11, 57, 40); 
times[3] = new DateTime(2014, 09, 1, 12, 00, 40);
times[4] = new DateTime(2014, 09, 1, 12, 01, 40);
times[5] = new DateTime(2014, 09, 1, 12, 12, 40);

var start = times[0];
var end = times[times.Length - 1];

var result = new List<DateTime>(); //The complete range
while (start <= end)
{
    result.Add(start);
    start = start.AddMinutes(1);
}

var missing = result.Except(times); //The missing datetimes

答案 1 :(得分:1)

你可以在第一次分钟后将所有东西都刮掉,以便得到分钟的开始。循环分钟并检查每分钟是否有时间,并添加缺少的分钟数。当它检查时间是否在分钟间隔内时,它适用于一分钟内的任何秒(甚至几分之一秒)。

DateTime[] times = new DateTime[6];
times[0] = new DateTime(2014, 09, 1, 11, 54, 40);
times[1] = new DateTime(2014, 09, 1, 11, 55, 45);
times[2] = new DateTime(2014, 09, 1, 11, 57, 40); // Minute 57
times[3] = new DateTime(2014, 09, 1, 12, 00, 10); // Minute 00 but next hour
times[4] = new DateTime(2014, 09, 1, 12, 01, 34);
times[5] = new DateTime(2014, 09, 1, 12, 12, 16);

DateTime t = times[0];
t = new DateTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, 0);
int i = 0;
while (i < times.Length) {
  if (times[i] < t) {
    Console.WriteLine(times[i++]);
  } else {
    if (times[i] < t.AddMinutes(1)) {
      Console.WriteLine(times[i++]);
    } else {
      Console.WriteLine(t);
    }
    t = t.AddMinutes(1);
  }
}

输出:

2014-09-01 11:54:40
2014-09-01 11:55:45
2014-09-01 11:56:00
2014-09-01 11:57:40
2014-09-01 11:58:00
2014-09-01 11:59:00
2014-09-01 12:00:10
2014-09-01 12:01:34
2014-09-01 12:02:00
2014-09-01 12:03:00
2014-09-01 12:04:00
2014-09-01 12:05:00
2014-09-01 12:06:00
2014-09-01 12:07:00
2014-09-01 12:08:00
2014-09-01 12:09:00
2014-09-01 12:10:00
2014-09-01 12:11:00
2014-09-01 12:12:16