R. Matveev -4 years ago 267
C# Question

# Calculate average timespan

I am to calculate average of a set of time spans, where each time span is a subtraction between two dates.

``````DateTime a = GetStartDateTime();
DateTime b = GetEndDateTime();

var delta = b.Subtract(a).TotalDays;
``````

Date format is like
`22.08.2016 21:00:00`

Is there any way to do this more rationally?

Also, I am curious why my
`delta`
is always like
`0.26914351851851853`
, in other words why it is not integer?

UPDATE:
Here is example time spans:

``````23.08.2016 10:31:38 - 22.08.2016 21:00:00
24.08.2016 14:32:26 - 24.08.2016 21:00:00
17.08.2016 8:36:51 - 01.01.2016 21:00:00
17.08.2016 8:34:27 - 15.03.2016 21:00:00
``````

Perform a simple mean calculation across the Ticks value of all your TimeSpans and create a new TimeSpan from the result. That will represent the average or mean TimeSpan. e.g.

``````        var timeSpanList = new List<TimeSpan>();
var provider = CultureInfo.InvariantCulture;
new TimeSpan(
DateTime.ParseExact("23.08.2016 10:31:38", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("22.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
new TimeSpan(
DateTime.ParseExact("24.08.2016 14:32:26", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("24.08.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:36:51", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("01.01.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
new TimeSpan(
DateTime.ParseExact("17.08.2016 8:34:27", "dd.MM.yyyy H:mm:ss", provider).Ticks -
DateTime.ParseExact("15.03.2016 21:00:00", "dd.MM.yyyy H:mm:ss", provider).Ticks));
var totalTicks = 0L;
foreach(var ts in timeSpanList)
{
totalTicks += ts.Ticks;
}
var avgTicks = totalTicks / timeSpanList.Count;
var avgTimeSpan = new TimeSpan(avgTicks);
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download