Free Information Technology Magazines and eBooks

Sunday, July 05, 2009

How to get the difference between two DateTime values in C#

One of the most common task of programmer when dealing with DATE and TIME is to comparing its values. In .NET, you deal with it using TimeSpan class which represents a time interval that can be in days, hours, minutes or seconds. Here is an example.


The following code uses TimeSpan and subtract one DateTime from another.


DateTime Date1 = new DateTime(2009, 6, 11);
DateTime Date2 = DateTime.Now;
TimeSpan timeSpan = Date2.Subtract(Date1);

// Display the difference of the two dates up to minutes
Console.WriteLine("Days : " + timeSpan.Days.ToString());
Console.WriteLine("Hours : " + timeSpan.Hours.ToString());
Console.WriteLine("Minutes : " + timeSpan.Minutes.ToString());

// You can also retrieve Total in Hours
Console.WriteLine("Total Hours " + timeSpan.TotalHours.ToString());



For more C# coding tips & tricks, subscribe now.

1 comments:

Wrecks said...

This code does not take into account changes in daylight savings time. See:

http://awesvb.blogspot.com/2009/04/difference-between-datestimes-including.html