In this code snippet, we will see how to calculate the difference between two dates in C#. We will use DateTime.Subtract() method to calculate the difference between two dates as shown below,
using System;
public class Example
{
public static void Main()
{
DateTime date1 = new DateTime(2020, 11, 12);
DateTime date2 = new DateTime(2020, 11, 15);
// Calculate difference between date 1 and date 2
TimeSpan timeSpan = date2.Subtract(date1);
// Print result
Console.WriteLine(timeSpan);
Console.WriteLine("Days difference = {0} ", timeSpan.TotalDays);
Console.ReadKey();
}
}
Output:
3.00:00:00
Days difference = 3
Comments (0)