简体   繁体   中英

What is the best way to divide two TimeSpan objects?

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

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.

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).

TimeSpan gained several new operators with the release of .NET Core 2.0 :

public TimeSpan Divide(double divisor);
public double Divide(TimeSpan ts);
public TimeSpan Multiply(double factor);

public static TimeSpan operator /(TimeSpan timeSpan, double divisor);
public static double operator /(TimeSpan t1, TimeSpan t2);
public static TimeSpan operator *(double factor, TimeSpan timeSpan);
public static TimeSpan operator *(TimeSpan timeSpan, double factor);

Of note, a TimeSpan can now be divided by another TimeSpan :

var a = new TimeSpan(10, 0, 0);
var b = new TimeSpan(0, 30, 0);
var c = new TimeSpan(0, 4, 30);

Console.WriteLine(a / b);
// Displays: "20"

Console.WriteLine(b / c);
// Displays: "6.66666666666667"

Make use of extension method can make codes more readable.

public static double DividedBy(this TimeSpan x, TimeSpan y)
{
    return Convert.ToDouble(x.Ticks) / y.Ticks;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM