1

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?

Al Woods
  • 113
  • 1
  • 3
  • 11
  • possible duplicate of [How to subtract a datetime from another datetime?](http://stackoverflow.com/questions/5177002/how-to-subtract-a-datetime-from-another-datetime) – Zong Nov 06 '13 at 19:45

2 Answers2

7

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.

Zong
  • 6,160
  • 5
  • 32
  • 46
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

To get the double you have to use TimeSpann.TotalHours, as Suggested by Jon Skeet:

TimeSpan timeSpann = date2 - date1;
Double difference = timeSpann.TotalHours;

TimeSpann.TotalHours

DROP TABLE users
  • 1,955
  • 14
  • 26