天日期的基础上,日期时间相差仅基础上、天日、日期、时间

2023-09-03 01:56:03 作者:何必怀念

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

I need to find the difference in days between two dates.

例如:

输入: **的startDate ** = 2012年12月31日23hr:59mn:分00秒,**结束日期** = 2013年1月1日00hr:1,500万:分00秒

期望的输出: 1

我试过如下:

(DT1-DT2).TotalDays ,并转换为整数,但并没有给我合适的答案为双已被转换为int - 试图Math.Ceiling,转换。为... dt1.day - dt2.day 整个月不工作 dt.Substract()具有与上述选项1相同的输出。 (dt1-dt2).TotalDays and convert to integer but didn't give me appropriate answer as double has to be converted to int - tried Math.Ceiling, Convert.To... dt1.day - dt2.day does not work across months dt.Substract() has the same output as option 1 mentioned above.

以上都不工作,所以我最后写以下code。在code效果很好,但我觉得必须有,只有一对夫妇的code线的解决方案。

None of the above worked, so I ended up writing the following code. The code works well, but I feel that there must be a solution with only a couple of lines of code.

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天

Note: I do not have any performance issue in the while-loop iteration as the max difference will not be more than 30 to 45 days.

推荐答案

嗯,这听起来像你想的天数的差异,忽略了时间的组成部分。 A 的DateTime 随着时间的组件重置为00:00:00是什么的 日期 属性为您提供了:

Well, it sounds like you want the difference in the number of days, ignoring the time component. A DateTime with the time component reset to 00:00:00 is what the Date property gives you:

(startDate.Date - endDate.Date).TotalDays
 
精彩推荐
图片推荐