The following code returns 9.25 when I feel it should return 8.25, what have I misunderstood?
(new DateTimeOffset(2014,09,04,08,15,00,new TimeSpan(0,0,0))).Subtract(new DateTimeOffset(2014,09,04,08,15,00,new TimeSpan(0,0,0)).Date).TotalHours
more simply shown as:-
DateTimeOffset start = new DateTimeOffset(2014,09,04,08,15,00,new TimeSpan(0,0,0));
double result = start.Subtract(start.Date).TotalHours
When run on a Windows 7 PC in Time Zone GMT (adjust for Daylight Saving time) on:-
12th September result = 9.25
12th December result = 8.25
The problem is that the DateTimeOffset.Date
property returns a DateTime
with a Kind
of unspecified. That's then assumed to be system-local when you subtract it from the DateTimeOffset
.
You can fix this by asking for the UtcDateTime
and get the Date
from that:
double result = start.Subtract(start.UtcDateTime.Date).TotalHours
Of course, that's assuming that the Date
that you want is the date on which the UTC date/time falls. We don't know much about your actual requirements. You might want to consider using my Noda Time library to avoid this sort of ambiguity though - with more types to choose from, it allows you to specify your intentions more clearly.
See more on this question at Stackoverflow