How to subtract one DateTime from Another and return a double of hours passed

So I have two DateTimes: date1 = 1/1/2000 12:00:00 AM date2 = 1/1/2000 12:30:00 AM

How can I subtract date2 from date1 and return a double of .5?

Jon Skeet
people
quotationmark

You can subtract one DateTime from another using the - operator (or use the Subtract method) to get a TimeSpan, then use TimeSpan.TotalHours:

DateTime start = new DateTime(2000, 1, 1, 0, 0, 0);
DateTime end = new DateTime(2000, 1, 1, 0, 30, 0);
TimeSpan difference = end - start;
Console.WriteLine(difference.TotalHours); // 0.5

Note that you do not want TimeSpan.Hours, which returns an int in the range -23 to 23 (inclusive); it's the "whole" number of hours.

people

See more on this question at Stackoverflow