c# - 仅基于日期的日期时间差异(以天为单位)

标签 c# .net c#-4.0

我需要找出两个日期之间的天数差。

例如:

输入:**startDate** = 12-31-2012 23hr:59mn:00sec, **endDate** = 01-01-2013 00hr:15mn:00sec

预期输出:1

我尝试了以下方法:

  1. (dt1-dt2).TotalDays 并转换为整数但没有给我适当的答案,因为必须将 double 转换为 int - 尝试过 Math.Ceiling、Convert.To...
  2. dt1.day - dt2.day 不能跨月工作
  3. dt.Substract() 具有与上述选项 1 相同的输出。

以上都不起作用,所以我最终编写了以下代码。代码运行良好,但我觉得必须有一个只有几行代码的解决方案。

public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
    {
        //Initializing with 0 as default return value
        int difference = 0;

        //If either of the dates are not set then return 0 instead of throwing an exception
        if (startDate == default(DateTime) | endDate == default(DateTime))
            return difference;

        //If the dates are same then return 0
        if (startDate.ToShortDateString() == endDate.ToShortDateString())
            return difference;

        //startDate moving towards endDate either with increment or decrement
        while (startDate.AddDays(difference).ToShortDateString() != endDate.ToShortDateString())
        {
            difference = (startDate < endDate) ? ++difference : --difference;
        }

        return difference;
    }

注意:我在 while 循环迭代中没有任何性能问题,因为最大差异不会超过 30 到 45 天。

最佳答案

嗯,听起来你想要天数的差异,忽略时间部分。时间组件重置为 00:00:00 的 DateTime 就是 Date 的内容属性(property)给你:

(startDate.Date - endDate.Date).TotalDays

关于c# - 仅基于日期的日期时间差异(以天为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13024458/

相关文章:

c# - 使用 WPF 和 SlimDx (DirectX 10/11)

c# - 如何在 C# 中使用 return 语句打开 wpf 窗口

c# - EF4 如何将一个表连接到两个或多个其他表

c# - await 不会按预期使用 StreamReader.ReadToEndAsync() 返回给调用者

c# - 为什么向结构体添加一个额外的字段会大大提高其性能?

c#-4.0 - 在 .asp 中转换 .htm 页面扩展名

c#-4.0 - 将 WSSE SOAP header 添加到 Web 引用

c# 反射返回 "Nullable` 1"

c# - 从 GetEnumSelectList<> 获取文本值而不是索引值

c# - 单元测试和检查私有(private)变量值