[英]C# DateTime calculation and ToString
我用時間做簡單的計算,看看這個過程已經運行了多長時間。
(DateTime.Now - StrtTime).ToString("hh:mm:ss")
其中StrtTime 是: DateTime StrtTime = DateTime.Now;
. 但我得到一個例外:
Input string was not in a correct format.
這樣做的正確方法是什么?
正如其他人所提到的,您可能想要使用StopWatch
。 但是,在您的特定情況下,您會遇到錯誤,因為在使用帶有TimeSpan.ToString
的格式化字符串時需要轉義“:”。 嘗試這個:
(DateTime.Now - StrtTime).ToString(@"hh\:mm\:ss")
嘗試使用
Stopwatch stpWatch1 = new Stopwatch();
stpWatch1.Start();
.............
stpWatch1.Stop();
TimeSpan ts = stpWatch1.Elapsed;// it also contains stpWatch1.ElapsedMilliseconds
正如安東尼所說,秒表更適合這項任務。 不過,要回答您的問題,您可以像這樣格式化日期:
String.Format("{0:hh:mm:ss}", (DateTime.Now - StrtTime).ToString());
使用秒表 class。
Stopwatch sw = new Stopwatch();
sw.Start();
//code
sw.Stop();
sw.Elapsed.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.