I seem to get different results when using the TimeSpan functionality in C# against TSQL DateDiff. It seems that DateDiff gives the number of days between 2 dates regardless of the time-stamp, whereas in C# it takes into consideration the timestamp. So if the 1st timestamp is at 10am, and the 2nd timestamp is at 9am the following day, the timespan is 0 days, whereas DateDiff will return 1.
declare @d1 datetime
declare @d2 datetime
set @d1 = '2/9/2011 10:00'
set @d2 = '2/10/2011 09:00'
select datediff(day, @d1, @d2)
-- prints 1
Using C# DateTime and DateTime span.
// will return 1 with same dates
private static int DateDiff(DateTime from, DateTime to)
{
return (new DateTime(from.Year, from.Month, from.Day)
- new DateTime(to.Year, to.Month, to.Day)).Days;
}
Question is, is there a better way to do this?
You could make your method shorter, like this: