【问题标题】:How can I emulate TSQL's DateDiff correctly in C#如何在 C# 中正确模拟 TSQL 的 DateDiff
【发布时间】: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;            
  }

问题是,有没有更好的方法来做到这一点?

【问题讨论】:

标签: c# tsql datetime


【解决方案1】:

你可以让你的方法更短,像这样:

private static int DateDiff(DateTime from, DateTime to)
{
    return (to.Date - from.Date).Days;            
}

【讨论】:

    【解决方案2】:
     public enum DateInterval
        {
            Second, Minute, Hour, Day, Week, Month, Quarter, Year
        }
    
      public long DateDiff(DateInterval Interval, System.DateTime StartDate, System.DateTime EndDate)
        {
            long lngDateDiffValue = 0;
            System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
            switch (Interval)
            {
                case DateInterval.Day:
                    lngDateDiffValue = (long)TS.Days;
                    break;
                case DateInterval.Hour:
                    lngDateDiffValue = (long)TS.TotalHours;
                    break;
                case DateInterval.Minute:
                    lngDateDiffValue = (long)TS.TotalMinutes;
                    break;
                case DateInterval.Month:
                    lngDateDiffValue = (long)(TS.Days / 30);
                    break;
                case DateInterval.Quarter:
                    lngDateDiffValue = (long)((TS.Days / 30) / 3);
                    break;
                case DateInterval.Second:
                    lngDateDiffValue = (long)TS.TotalSeconds;
                    break;
                case DateInterval.Week:
                    lngDateDiffValue = (long)(TS.Days / 7);
                    break;
                case DateInterval.Year:
                    lngDateDiffValue = (long)(TS.Days / 365);
                    break;
            }
            return (lngDateDiffValue);
        }//end of DateDiff
    

    我发现这个方法对我有用。

    【讨论】:

      【解决方案3】:

      类似这样的:

      private static int DateDiff(DateTime From, DateTime To)
      {
          return From.Subtract(To).Days;            
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-30
        • 1970-01-01
        • 2019-10-09
        • 2020-11-07
        相关资源
        最近更新 更多