gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:31:12 25 4
gpt4 key购买 nike

在针对 TSQL DateDiff 使用 C# 中的 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 跨度。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com