计算两个日期之间的日历月数 [英] Calculate the number of Calendar Months between two dates
本文介绍了计算两个日期之间的日历月数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用C#开发兴趣计算器。我需要知道2个日期之间的天数
I am developing a interest calculator in C#. I need to know the number of days between 2 dates
所以,我在计算这样的内容:
So, I am calculating something like this :
DateTime dt1 = DateTime.ParseExact(DateTime.Now.Date.ToString("dd-MM-yy"), "dd-MM-yy", CultureInfo.InvariantCulture).Date;
DateTime dt2 = DateTime.ParseExact(Duration, "dd-MM-yy", CultureInfo.InvariantCulture).Date;
Double no_days = (dt1 - dt2).TotalDays;
但是,取决于月份,天数会有所不同。因此,即使天数少于30天,2月15日至3月15日仍构成一个月。
However, depending on the month, the number of days would vary. So, Feb 15 to Mar 15 constitute a month even though the number of days is less than 30.
任何想法如何确定经过的月数?利息计算是在每月持续时间结束时完成的。
Any ide how I can determine the number of months elapsed ? The interest calculation is done at the end of the month duration.
谢谢
推荐答案
我想不出比这更干净的方法:
I can't think of any cleaner way than this:
((dt1.Year - dt2.Year) * 12) + (dt1.Month - dt2.Month) - (dt1.Day < dt2.Day?1:0);
即使那样,我不确定我是否错过了一些边缘案例。
And even then, I'm not sure if I've maybe missed some edge cases.
这篇关于计算两个日期之间的日历月数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文