示例:给定以下两个日期,结束日期始终大于或等于开始日期
start = 2001 年 1 月 1 日
完成=2002年3月15日
所以从2001年1月1日到2002年2月底
月 =12 + 2 = 14
2002年3月
15/30 = 0.5
所以总计是14.5月差异。
手动计算很容易,但是如何优雅地编写代码呢?目前,我结合了很多 if else 和 while 循环来实现我想要的,但我相信还有更简单的解决方案。
Update:输出需要是precise(不是近似值)例如:
如果从 2001 年 1 月 1 日开始,到 2001 年 4 月 16 日结束,则输出应为 1 + 1 + 1= 3(对于一月、二月和三月),并且 16 / 31 = 0.516 个月,因此总数为 3.516。
另一个例子是,如果我从 2001 年 7 月 5 日开始,到 2002 年 7 月 10 日结束,那么输出应该是到 2002 年 6 月结束为止的 11 个月,并且 (31-5)/31 = 0.839 和 10/31 = 0.323 个月,所以总数是 11 + 0.839 + 0.323 = 12.162。
我延长了乔什·斯托多拉的代码和高科技骑士's code:
public static decimal GetMonthsInRange(this IDateRange thisDateRange)
{
var start = thisDateRange.Start;
var finish = thisDateRange.Finish;
var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1;
decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month);
decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month);
var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth;
var daysApartInFinishMonth = finish.Day/daysInFinishMonth;
return monthsApart + daysApartInStartMonth + daysApartInFinishMonth;
}
我给了一个int
之前回答过,然后意识到你要求更准确的答案。我累了,所以我删除了并上床睡觉。这么多,我无法入睡!出于某种原因,这个问题确实困扰着我,我必须解决它。所以你来吧...
static void Main(string[] args)
{
decimal diff;
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2002, 3, 15));
Console.WriteLine(diff.ToString("n2")); //14.45
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2001, 4, 16));
Console.WriteLine(diff.ToString("n2")); //3.50
diff = monthDifference(new DateTime(2001, 7, 5), new DateTime(2002, 7, 10));
Console.WriteLine(diff.ToString("n2")); //12.16
Console.Read();
}
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
int monthsApart = Math.Abs(12 * (d1.Year-d2.Year) + d1.Month - d2.Month) - 1;
decimal daysInMonth1 = DateTime.DaysInMonth(d1.Year, d1.Month);
decimal daysInMonth2 = DateTime.DaysInMonth(d2.Year, d2.Month);
decimal dayPercentage = ((daysInMonth1 - d1.Day) / daysInMonth1)
+ (d2.Day / daysInMonth2);
return monthsApart + dayPercentage;
}
现在我将做一个甜蜜的梦。晚安 :)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)