[英]Problem finding difference between two time intervals
如何找到兩個時間間隔之間的差異。 像13:45:26.836-14:24:18.473,其格式為“小時:分鍾:秒:毫秒”。 現在,我需要找到這兩次之間的時差。
我如何在C#中做到這一點?
提前致謝。
基本上,您需要做的就是將這些時間值放入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();
TimeSpan具有大量可獲取設置的屬性-各種單位之間的差異,例如毫秒,秒,分鍾等。您也可以對它執行.ToString()
以獲取結果的字符串表示形式。 在result2
,您將獲得以下內容:
00:38:51.6370000
那是您要找的東西嗎?
我正在舉一個例子;
您可以檢查它並修改您的程序,
/* 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);
查找秒數; 減去兩個數字,便可以計算出時差。 根據您使用的編程語言,我確定它們必須是可以處理它的庫。
//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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.