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?
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?
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.
To get the double you have to use TimeSpann.TotalHours
, as Suggested by Jon Skeet:
TimeSpan timeSpann = date2 - date1;
Double difference = timeSpann.TotalHours;