How to find the average duration from these values?

  • Thread starter Thread starter jarosciak
  • Start date Start date
J

jarosciak

Hi everyone,

I need a little bit of help with this problem.


I've got a time durations feed, which comes in this format
(minutes:seconds):


Example, there is only 5 values:
00:45
01:15
00:12
00:53
03:42


I need to find the average duration from these 5 values.


Can someone help me to figure out how to do this in C#.NET?


Thanks
Joe
 
Hi Joe,

This is just sample code but you could adapt it to your needs. One
approach is to use TimeSpan.Parse( ) to get what you want. You'll need
to be careful that the input strings are all formatted correctly. The
TimeSpan.Parse( ) routine expects hh:mm and not mm:ss, so I prepended
"00:" for the hours. Then it's just a matter of doing the average:

string[] times = { "00:45", "01:15" , "00:12", "00:53", "03:42" };
TimeSpan totalTime = new TimeSpan();
foreach (string time in times)
totalTime += TimeSpan.Parse("00:" + time);
long averageTicks = (totalTime.Ticks / times.Length);
Console.WriteLine("The average is {0}", new TimeSpan(averageTicks));

Like I said, you'll probably want to do some error handling in there
but you get the gist.
Hope that helps,
John
 
Back
Top