Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, May 15, 2008 12:47 PM
For my project I am given multiple times such as 11:49, 11:17, 10:36. How can I average that total? So it comes out to 11:14? I am using Visual Studio 2008, Visual C# any help would be appricated
All replies (9)
Thursday, May 15, 2008 3:17 PM âś…Answered | 1 vote
DateTime date1 = new DateTime(2008, 5, 15, 11, 49, 0);
DateTime date2 = new DateTime(2008, 5, 15, 11, 17, 0);
DateTime date3 = new DateTime(2008, 5, 15, 10, 36, 0);
DateTime medium = new DateTime((date1.Ticks + date2.Ticks + date3.Ticks) / 3);
Thursday, May 15, 2008 12:52 PM
Hi, Nathan,
Here is sample:
1. Convert datetimes to UTC. In this case you will have array of integers.
2. Find average value in this array.
3. Convert average integer from UTC to datetime.
Thursday, May 15, 2008 1:59 PM
I am confused on how this would make it easier can you show me an actual code example because I still not get that. You are still trying to average a time. Maybe i just do not see how this can work please explain more thanks.
~Nathan
Thursday, May 15, 2008 2:10 PM
Nathan,
As far as I understand, you need to calculate average time, correct?
UTC is integer representation of datetime. It is very easy to calculate average of set of integers.
Thursday, May 15, 2008 2:25 PM
yes that is correct but doesn't UTC stand for Universal Time Code so i am still dealing with a datetime. So how do you through that data into an array.
~Nathan
Thursday, May 15, 2008 3:27 PM | 1 vote
Use the Ticks property - add them all up and average them.
NOTE: It's a long, and it could overflow if you add lots of them up, in which case you could divide the values by (say) 1000 before adding them all up and dividing by N, and then multiply the final result by 1000.
The tick count is the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 - so you should be able to divide all the numbers by at least 1000 before losing too much precision.
Thursday, May 15, 2008 3:43 PM
Nathan,
I meant using DateTime.ToFileTimeUtc method. It returns long which you can use to calculate average.
Monday, June 28, 2010 12:44 PM
@Matthew Watson - Your answer helped me with the overflow exception. It can be easily thrown. I was calculating average of 17 dates and I got this exception.
Thanks
Monday, June 28, 2010 2:41 PM
If the date part is not relevant, you should use TimeSpan.
You can add millions of timespan of less than a day before reaching maxvalue.