Monday, March 15, 2021

Calculate Date and Time Difference Between Two Dates C#

A very common requirement is to display the Date and Time difference between two dates. 
Let us see how to do it:

C#

public class Program
{
public static void Main()
{
   DateTime date1 = 
   System.Convert.ToDateTime("2009-1-01 11:08:22");

   DateTime date2 = 
   System.Convert.ToDateTime("2009-1-02");

   TimeSpan ts = new TimeSpan();

   ts = date2.Subtract(date1);

   Console.WriteLine(ts.Days + " Days "  + ts.Hours + " Hours " +   ts.Seconds + " Seconds ");        

}
}


Output:

 0 Days 12 Hours 38 Seconds 

No comments: