Sabari M Sabari M
Updated date Feb 22, 2021
In this code snippet, we will see how to calculate the difference between two dates in C#. It helps for the C# fresh or experienced developers who want to calculate the difference between 2 dates .

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

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!