Reputation: 27350
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?
Upvotes: 2
Views: 1640
Reputation: 31239
Something like this:
private static int DateDiff(DateTime From, DateTime To)
{
return From.Subtract(To).Days;
}
Upvotes: 0
Reputation: 6030
public enum DateInterval
{
Second, Minute, Hour, Day, Week, Month, Quarter, Year
}
public long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
{
long lngDateDiffValue = 0;
System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
switch (Interval)
{
case DateInterval.Day:
lngDateDiffValue = (long)TS.Days;
break;
case DateInterval.Hour:
lngDateDiffValue = (long)TS.TotalHours;
break;
case DateInterval.Minute:
lngDateDiffValue = (long)TS.TotalMinutes;
break;
case DateInterval.Month:
lngDateDiffValue = (long)(TS.Days / 30);
break;
case DateInterval.Quarter:
lngDateDiffValue = (long)((TS.Days / 30) / 3);
break;
case DateInterval.Second:
lngDateDiffValue = (long)TS.TotalSeconds;
break;
case DateInterval.Week:
lngDateDiffValue = (long)(TS.Days / 7);
break;
case DateInterval.Year:
lngDateDiffValue = (long)(TS.Days / 365);
break;
}
return (lngDateDiffValue);
}//end of DateDiff
I found this method works for me.
Upvotes: 0
Reputation: 120937
You could make your method shorter, like this:
private static int DateDiff(DateTime from, DateTime to)
{
return (to.Date - from.Date).Days;
}
Upvotes: 3