TechieClues TechieClues
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 .
  • 1.7k
  • 0
  • 0

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

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

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