[英]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). 我想得到一个TimeSpan与另一个TimeSpan的比率(基本上是从它的总时间开始播放视频的进度)。 My current methods is to get the milliseconds of the two TimeSpan objects and divide one against the other.
我目前的方法是获取两个TimeSpan对象的毫秒数,并将一个对象除以另一个。 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. 您必须将一个转换为double,否则C#将执行整数除法。 Ticks is better than the TotalMilliseconds because that is how it is stored and avoids any conversion.
刻度优于TotalMilliseconds,因为它是如何存储的,并避免任何转换。
You should use either Ticks or TotalMilliseconds , depending on the required precision. 您应该使用Ticks或TotalMilliseconds ,具体取决于所需的精度。 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 : 随着.NET Core 2.0的发布,
TimeSpan
获得了几个新的运营商:
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
: 值得注意的是,
TimeSpan
现在可以被另一个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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.