C# 兩個 DateTime 之間的毫秒級差值


假設以下兩個 DateTime 物件是我們的日期。

DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);

使用 TimeSpan 找出這兩個日期之間的差值。

TimeSpan ts = date2 - date1;

現在,要獲得毫秒數,請使用以下屬性 -

ts.TotalMilliseconds

讓我們看看完整的程式碼。

例項

 即時演示

using System;
using System.Linq;
public class Demo {
   public static void Main() {
      DateTime date1 = new DateTime(2018, 8, 11, 08, 15, 20);
      DateTime date2 = new DateTime(2018, 8, 11, 11, 14, 25);
      TimeSpan ts = date2 - date1;
      Console.WriteLine("No. of Seconds (Difference) = {0}", ts.TotalMilliseconds);
   }
}

輸出

No. of Seconds (Difference) = 10745000

更新日期: 2020 年 6 月 23 日

7K+ 瀏覽次數

啟動您的職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.