How to find date difference in C#?


To find the difference between two dates in C#, you need to first set two dates to be compared using the DateTime object. We will use the DateTime class in C#.

Date 1

DateTime date1 = new DateTime(2018, 09, 15);
Console.WriteLine("Date 1 : {0}", date1);

Date 2

DateTime date2 = new DateTime(2018, 09, 28);
Console.WriteLine("Date 2 : {0}", date2);

Now let us compare both the dates in C#. The following is an example to compare dates in C#.

Example

 Live Demo

using System;
namespace Program {
   class Demo {
      static int Main() {
         DateTime date1 = new DateTime(2018, 09, 15);
         Console.WriteLine("Date 1 : {0}", date1);

         DateTime date2 = new DateTime(2018, 09, 28);
         Console.WriteLine("Date 2 : {0}", date2);
         if (date1 < date2)
         Console.WriteLine("{0} comes before {1}", date1, date2);
         Console.Read();
         return 0;

      }
   }
}

Output

Date 1 : 9/15/2018 12:00:00 AM
Date 2 : 9/28/2018 12:00:00 AM
9/15/2018 12:00:00 AM comes before 9/28/2018 12:00:00 AM

Updated on: 22-Jun-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements