Đặt hai ngày.
DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20); DateTime date2 = new DateTime(2018, 7, 15, 11, 14, 25);
Bây giờ hãy tính toán sự khác biệt giữa hai ngày.
TimeSpan ts = date2 - date1;
Tiến xa hơn và tính toán sự khác biệt trong vài giây.
ts.TotalSeconds
Hãy cho chúng tôi xem mã hoàn chỉnh.
Ví dụ
using System;
using System.Linq;
public class Demo {
public static void Main() {
DateTime date1 = new DateTime(2018, 7, 15, 08, 15, 20);
DateTime date2 = new DateTime(2018, 7, 15, 11, 14, 25);
TimeSpan ts = date2 - date1;
Console.WriteLine("No. of Seconds (Difference) = {0}", ts.TotalSeconds);
}
} Đầu ra
No. of Seconds (Difference) = 10745