DateTime仅以日期为基础的天数差异

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

例如:

输入: **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的DateTimeDate属性为您提供的:

 (startDate.Date - endDate.Date).TotalDays 

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

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

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

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

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

 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 } 

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

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

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

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

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