簡體   English   中英

划分兩個TimeSpan對象的最佳方法是什么?

[英]What is the best way to divide two TimeSpan objects?

我想得到一個TimeSpan與另一個TimeSpan的比率(基本上是從它的總時間開始播放視頻的進度)。 我目前的方法是獲取兩個TimeSpan對象的毫秒數,並將一個對象除以另一個。 就像是:

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

        Double progressRatio = progressInMilliseconds / durationInMilliseconds;

有更直接的路線嗎? 這是一個簡單的問題,我只是好奇,如果有一個超級優雅的方式來解決它。

為所有詹姆斯干杯

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

您必須將一個轉換為double,否則C#將執行整數除法。 刻度優於TotalMilliseconds,因為它是如何存儲的,並避免任何轉換。

您應該使用TicksTotalMilliseconds ,具體取決於所需的精度。 毫秒是超過當前秒數的毫秒數。

至於更好的解決方案,它並不比分區簡單,因此您當前的解決方案很好(減去錯誤)。

隨着.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);

值得注意的是, 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"

利用擴展方法可以使代碼更具可讀性。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM