在 C# 中针对 TSQL DateDiff 使用 TimeSpan 功能时,我似乎得到了不同的结果。似乎 DateDiff 给出了 2 个日期之间的天数,而与时间戳无关,而在 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 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;
}
问题是,有更好的方法吗?
最佳答案
您可以使您的方法更短,如下所示:
private static int DateDiff(DateTime from, DateTime to)
{
return (to.Date - from.Date).Days;
}
关于c# - 如何在 C# 中正确模拟 TSQL 的 DateDiff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364933/