【发布时间】:2012-03-11 00:26:06
【问题描述】:
在针对 TSQL DateDiff 使用 C# 中的 TimeSpan 功能时,我似乎得到了不同的结果。无论时间戳如何, DateDiff 似乎都给出了两个日期之间的天数,而在 C# 中它考虑了时间戳。因此,如果第一个时间戳是上午 10 点,第二个时间戳是第二天上午 9 点,则时间跨度为 0 天,而 DateDiff 将返回 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
使用 C# DateTime 和 DateTime 跨度。
// 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;
}
问题是,有没有更好的方法来做到这一点?
【问题讨论】:
-
这是因为 DATEDIFF 返回跨越的此类边界的数量。 DATEDIFF (Transact SQL)