【问题标题】:How does the EntityFunctions.DiffHours method work?EntityFunctions.DiffHours 方法是如何工作的?
【发布时间】:2014-06-12 18:05:38
【问题描述】:

我在文档中找不到任何解释此方法细节的内容。因为它总是返回一个整数,所以它不区分 3:20 的时差和 3:10 的时差。但它是向上取整还是向下取整,还是仅比较 2 次的小时数部分?

示例: 开放时间 = 2014-06-12 13:35:00.000 关闭时间 = 2014-06-13 14:30:00.000

实际差异是 24 小时 55 分钟。这会返回 24 小时还是 25 小时的差异?

我需要确定 2 次是否相隔 25 小时或更长时间;我可以为此使用 DiffHours,还是需要使用 DiffSeconds 并将结果除以 3600 才能得到实际小时数?

【问题讨论】:

  • Will this return a difference of 24 hours, or 25 hours? 当你自己尝试这个时会发生什么?
  • 25。但我不知道这是因为它是从 24.92 向上取整,还是因为它比较了开盘时的“13”和收盘时的“14”,而完全忽略了分钟。
  • 无论如何都是意外行为;这 2 次之间的差异小于 25 小时。
  • 它将最终转换为执行工作的 SQL 语句,因此如果您使用 SQL Profiler 进行跟踪,您可以看到它到底做了什么。

标签: .net entity-framework datetime timespan


【解决方案1】:

EF 的一个优点是它完全是开源的。如果你翻遍this part of the source code,你会发现:

functionHandlers.Add("DiffHours", HandleCanonicalFunctionDateDiff);

调用:

// <summary>
// Handler for all date/time addition canonical functions.
// Translation, e.g.
// DiffYears(datetime, number) =>  DATEDIFF(year, number, datetime)
// </summary>
private static ISqlFragment HandleCanonicalFunctionDateDiff(SqlGenerator sqlgen, DbFunctionExpression e)
{
    var result = new SqlBuilder();

    result.Append("DATEDIFF (");
    result.Append(_dateDiffFunctionNameToDatepartDictionary[e.Function.Name]);
    result.Append(", ");
    result.Append(e.Arguments[0].Accept(sqlgen));
    result.Append(", ");
    result.Append(e.Arguments[1].Accept(sqlgen));
    result.Append(")");

    return result;
}

所以这就是你的答案 - 调用 EntityFunctions.DiffHours 只是转换为调用 native DATEDIFF function in SQL Server

由于DATEDIFF 通过计算日期部分边界来工作,因此它只是截断所有秒数并仅比较年、月、日和小时部分。

证明:

SELECT DATEDIFF(hour,'2014-01-01 00:00:00','2014-01-01 01:00:00')
-- returns 1 hour

SELECT DATEDIFF(hour,'2014-01-01 00:00:00','2014-01-01 01:01:00')
-- returns 1 hour

SELECT DATEDIFF(hour,'2014-01-01 00:00:00','2014-01-01 01:59:00')
-- returns 1 hour

SELECT DATEDIFF(hour,'2014-01-01 00:00:00','2014-01-01 00:59:00')
-- returns 0 hours

【讨论】:

  • 谢谢!我想我必须调用 DiffSeconds 然后除以 3600。很遗憾他们没有提供等效的 TimeSpan.TotalHours 属性。
猜你喜欢
  • 2013-03-11
  • 2019-05-20
  • 2012-04-21
  • 2016-07-26
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多