A blog about my experience in the IT world.

[C#] How to calculate multiple DateTime average

September 23, 2011

After googling around I couldn't find any good solution for the problem.

Found a few suggestions of converting a DateTime value into ticks that could work. But given a large enough  number of DateTimes there isn't a data type big enough to hold the cumulative value needed to calculate the average, since there are 10.000k ticks in a second.

So, took a little shortcut and used an identical approach with seconds instead:


public DateTime averageDateTime(List collection)
{
double totalSec = 0;
for (int i = 0; i < collection.Count(); i++)
{
TimeSpan ts = collection[i].Subtract(DateTime.MinValue);
totalSec += ts.TotalSeconds;
}
double averageSec = totalSec / collection.Count();
DateTime averageDateTime = DateTime.MinValue.AddSeconds(averageSec);
return averageDateTime;
}

Solved!

0 comentários: