Use DateTime.Subtract to get the difference between two dates in C#.
Firstly, set two dates −
DateTime date1 = new DateTime(2018, 8, 27); DateTime date2 = new DateTime(2018, 8, 28);
Use the Subtract method to get the difference −
TimeSpan t = date2.Subtract(date1);
The following is the complete code −
Example
using System;
using System.Threading;
using System.Diagnostics;
public class Demo {
public static void Main() {
DateTime date1 = new DateTime(2018, 8, 27);
DateTime date2 = new DateTime(2018, 8, 28);
// getting the difference
TimeSpan t = date2.Subtract(date1);
Console.WriteLine(t);
Console.WriteLine("Days (Difference) = {0} ", t.TotalDays);
Console.WriteLine("Minutes (Difference) = {0}", t.TotalMinutes);
}
}Output
1.00:00:00 Days (Difference) = 1 Minutes (Difference) = 1440