2010-05-07 63 views
1

如何找到兩個時間間隔之間的差異。 像13:45:26.836 - 14:24:18.473格式爲「小時:分鐘:秒:毫秒」。現在我需要找到這兩次之間的時差。發現兩個時間間隔之間的差異

如何在C#中執行此操作?

在此先感謝。

+0

哪種語言,框架? – 2010-05-07 04:32:03

+0

語言:VS2005中的C# – SyncMaster 2010-05-07 04:36:27

回答

4

基本上,你需要做的是把那些時間值轉換爲DateTime結構。一旦你有你的兩個DateTime變量,只是彼此相減 - 結果是TimeSpan類型的變量:

DateTime dt1 = new DateTime(2010, 5, 7, 13, 45, 26, 836); 
DateTime dt2 = new DateTime(2010, 5, 7, 14, 24, 18, 473); 

TimeSpan result = dt2 - dt1; 
string result2 = result.ToString(); 

時間跨度有一噸是得到屬性集 - 在各種單位的差異,例如毫秒,秒,分鐘等。您也可以對其執行.ToString()以獲得結果的字符串表示形式。在result2,你會得到這樣的事情:

00:38:51.6370000 

這就是你想要的?

0

查找秒數;減去兩個數字,然後你可以計算出時間差。根據你使用的編程語言,我肯定他們必須是一個能夠處理它的庫。

1

我發佈一個例子;

您可以檢查和調整程序,

/* Read the initial time. */ 
    DateTime startTime = DateTime.Now; 
    Console.WriteLine(startTime); 

    /* Do something that takes up some time. For example sleep for 1.7 seconds. */ 
    Thread.Sleep(1700); 

    /* Read the end time. */ 
    DateTime stopTime = DateTime.Now; 
    Console.WriteLine(stopTime); 

    /* Compute the duration between the initial and the end time. 
    * Print out the number of elapsed hours, minutes, seconds and milliseconds. */ 
    TimeSpan duration = stopTime - startTime; 
    Console.WriteLine("hours:" + duration.Hours); 
    Console.WriteLine("minutes:" + duration.Minutes); 
    Console.WriteLine("seconds:" + duration.Seconds); 
    Console.WriteLine("milliseconds:" + duration.Milliseconds); 
0
//Start off with a string 
string time1s = "13:45:26.836"; 
string time2s = "14:24:18.473"; 

TimeSpan interval = DateTime.Parse(time2s) - DateTime.Parse(time1s); 

這將產生的結果是:

Days 0 int   Hours 0 int 
    Milliseconds 637 int 
    Minutes 38 int   Seconds 51 int 
    Ticks 23316370000 long 
    TotalDays 0.02698653935185185 double 
    TotalHours 0.64767694444444446 double 
    TotalMilliseconds 2331637.0 double 
    TotalMinutes 38.860616666666665 double 
    TotalSeconds 2331.6369999999997 double 
相關問題