c# - 如何在 C# 中正确模拟 TSQL 的 DateDiff

标签 c# t-sql datetime

在 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/

相关文章:

sql-server - 返回日期为 null 作为 t-sql 中的最大值

sql - 如何查询所有数据库中表中的某一列

c# - 如何检查相同的日期是否已在列表中?

c# - 如何防止 C# 中的 Gremlin 注入(inject)?

sql-server - 用于计算过去 10 分钟内出现次数的窗口函数

c# - AES:使用CCCrypt()方法加密,使用C#解密,输出错误

sql - 如何比较 SQL Server 中的日期时间与仅日期

python - 如何在python中打印时间和日期

c# - 使用 LINQ 或 Lambda 从列表中删除实例?

c# - 无法将控件添加到用户控件