How to find the average duration from these values?

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
 
J

John Duval

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
 
J

jarosciak

This had helped a lot and I was able to figure it out.
Thank you so much.
Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top