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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13024458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:23:45  来源:igfitidea点击:

DateTime difference in days on the basis of Date only

c#.netc#-4.0

提问by StartingFromScratch

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

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

For example:

例如:

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

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

Expected output: 1

预期输出: 1

I tried the following:

我尝试了以下方法:

  1. (dt1-dt2).TotalDaysand convert to integer but didn't give me appropriate answer as double has to be converted to int - tried Math.Ceiling, Convert.To...
  2. dt1.day - dt2.daydoes not work across months
  3. dt.Substract()has the same output as option 1 mentioned above.
  1. (dt1-dt2).TotalDays并转换为整数,但没有给我适当的答案,因为 double 必须转换为 int - 尝试过 Math.Ceiling、Convert.To ...
  2. dt1.day - dt2.day跨月不起作用
  3. dt.Substract()具有与上述选项 1 相同的输出。

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;
    }

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.

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

采纳答案by Damien_The_Unbeliever

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

好吧,听起来您想要天数的差异,而忽略时间部分。一个DateTime与时间部分复位00:00:00是个什么Date属性为您提供:

(startDate.Date - endDate.Date).TotalDays

回答by Habib

Use TimeStamp. Just subtract two dates (using DateTime.Dateproperty), get the difference in time span and return TotalDays

使用时间戳。只需减去两个日期(使用DateTime.Date属性),得到时间跨度的差异并返回TotalDays

TimeSpan ts = endDate.Date - startDate.Date;
double TotalDays = ts.TotalDays;

So your extension method can be as simple as:

所以你的扩展方法可以很简单:

public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
    {
      return (int) (endDate.Date - startDate.Date).TotalDays;
      // to return just a int part of the Total days, you may round it according to your requirement
    }

EDIT:Since the question has been edited, you may check the following example. Consider the following two dates.

编辑:由于问题已被编辑,您可以查看以下示例。考虑以下两个日期。

DateTime startDate = new DateTime(2012, 12, 31, 23, 59, 00);
DateTime endDate = new DateTime(2013, 01, 01, 00, 15, 00); 

You can write the extension method as:

您可以将扩展方法编写为:

public static int GetDifferenceInDaysX(this DateTime startDate, DateTime endDate)
    {
        TimeSpan ts = endDate - startDate;
        int totalDays = (int) Math.Ceiling(ts.TotalDays);
        if (ts.TotalDays < 1 && ts.TotalDays > 0)
            totalDays = 1;
        else
            totalDays = (int) (ts.TotalDays);
        return totalDays;
    }

For the above dates it will give you 1

对于上述日期,它会给你 1

回答by Amiram Korach

If you use the DateTime.Dateproperty this will eliminate the time

如果您使用该DateTime.Date属性,这将消除时间

date1.Date.Subtract(date2.Date).Days