2010-06-11 59 views
3

如何扣除兩個日期並獲取返回的TimeSpan對象的總小時數?獲取TimeSpan中的總小時數

例如,如果時間跨度爲2天,總時間爲48

+3

是不是隻是TimeSpan的TotalHours屬性,即'(Date1 - Date2).TotalHours'?或者我誤解了這個問題? – Rup 2010-06-11 14:20:13

回答

7

然後你想要的TimeSpan對象的TotalHours屬性:

DateTime today = DateTime.Today; 
DateTime twoDaysAgo = today.AddDays(-2.0); 

// returns 48.0 
double totalHours = (today - twoDaysAgo).TotalHours; 
+1

不能不提的是,雖然這個編譯和運行,但還是有一些疑問:時區。 – Aron 2013-08-05 03:46:43

0

我這樣做的:

int day = Tempo.Days; 
int Hours = Tempo.Hours; 
if (day > 0) 
{ 
    for (int i = 0; i < day; i++) 
    { 
    Hours += 24; 
    } 
} 
string minuto = (Tempo.Minutes < 9) ? "0" + Tempo.Minutes.ToString() : Tempo.Minutes.ToString(); 
string segundos = (Tempo.Seconds < 9) ? "0" + Tempo.Seconds.ToString() : Tempo.Seconds.ToString(); 
string texto = Hours.ToString() + ":" + minuto + ":" + segundos; 
+0

過度工作,改用'.TotalHours'或'.ToString(String)'。 https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings – user6537157 2017-11-24 16:34:54