Home / Programming / Blog article: Code Sample: Find Difference Between Two DateTime Values

| RSS

Code Sample: Find Difference Between Two DateTime Values

September 17th, 2008 | No Comments | Posted in Programming

This code shows you how to find the difference between two DateTime values. The easiest way to do this is to use the TimeSpan class and subtract one DateTime from another.

DateTime firstDate = new DateTime(2008, 8, 1);
DateTime secondDate = DateTime.Now;

TimeSpan timeSpan = secondDate.Subtract(firstDate);

// Get Difference 
Console.WriteLine("Days : " + timeSpan.Days.ToString());
Console.WriteLine("Hours : " + timeSpan.Hours.ToString());
Console.WriteLine("Minutes : " + timeSpan.Minutes.ToString());

// Get Total Hours
Console.WriteLine("Total Hours " + timeSpan.TotalHours.ToString());

Here is the output.

image

Note the difference between Hours and TotalHours.

Leave a Reply 4512 views, 1 so far today |
Tags:

Leave a Reply





Switch to our mobile site