C# Program to get the difference between two dates


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

 Live Demo

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

Updated on: 22-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements