Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to divide two TimeSpan objects?

Tags:

c#

I want to get the ratio of one TimeSpan against another TimeSpan (Basically the progress of a playing video from it's total time). My current methods is to get the milliseconds of the two TimeSpan objects and divide one against the other. Something like:

        int durationInMilliseconds = totalTimeSpan.Milliseconds;
        int progressInMilliseconds = progressTimeSpan.Milliseconds;

        Double progressRatio = progressInMilliseconds / durationInMilliseconds;

Is there a more direct route? It's a simple problem and i'm just curious if there is a super elegant way to solve it.

Cheers all James

like image 864
James Hay Avatar asked Sep 10 '09 14:09

James Hay


2 Answers

double progressRatio = progressTimeSpan.Ticks / (double)totalTimeSpan.Ticks;

You must cast one to a double, otherwise C# will do integer division. Ticks is better than the TotalMilliseconds because that is how it is stored and avoids any conversion.

like image 180
JDunkerley Avatar answered Nov 15 '22 20:11

JDunkerley


You should use either Ticks or TotalMilliseconds, depending on the required precision. Milliseconds is the number of milliseconds past the current second.

As for a better solution, it doesn't get simpler than a division so your current solution is fine (minus the bug).

like image 39
Richard Szalay Avatar answered Nov 15 '22 21:11

Richard Szalay