2016-05-13 145 views
0

我正在寻找一种方法来计算两个日期之间每个月的30天之间的天数(即使在二月,在31月)。计算两个日期之间的所有月份= 30天的数字

在SQL中有一些解决方案,但如果可能的话,我正在寻找c#中的解决方案。 有什么想法吗?

实施例:(DATE US)

2016年1月1日到2016年5月31日= 150天,而不是150

,因为在这种情况下5一个月,所以5 * 30 = 150. 所有月份都基于我的情况30天。

其它示例:

从2016年1月16日到2016年7月17日182 =代替的183(15 + 30 + 30 + 30 + 30 + 30 + 17)

+2

看起来很奇怪,为什么你想挑战的日历,使所有个月30天?添加更多关于你想要达到的细节将有助于理解它。 –

+0

您可以获取DateTime对象的月份编号,该对象将返回1到12之间的数字。如果您计算11月至2月的月份,则可能还需要查看年份。 – jdweng

+2

有这么多的特例要考虑,没有希望以明智的方式回答这个问题。至少为你能想到的角落案例提供一些输入和预期输出。 – hvd

回答

0

试这个代码

var months = endDate.Month - startDate.Month - 1; 
var startDateDayes = 30 - startDate.Day; 
startDateDayes =startDateDayes ==-1 ? 0 : startDateDayes;//for 31 month days 
var endDateDayes = endDate.Day; 
var totalDays = startDateDayes + endDateDayes + months * 30; 
if (endDate.Year > startDate.Year) 
{ 
    totalDays += 360 * (endDate.Year - startDate.Year); 
} 

希望它有助于

1

什么你正在试图做的似乎是用于金融市场相同的日历。下面是实现30E/360 ISDA计算方法,因为它是在他们在其网站上提供demo XLS实施的解决方案(30/360天数计算惯例):

var start = new DateTime(2016, 1, 1); 
var finish = new DateTime(2016, 05, 31); 


var d1 = start.Day == 31 ? 30 : start.Day; 
var d2 = finish.Day == 31 && (start.Day == 30 || start.Day == 31) ? 30 : finish.Day; 
// actualDaysDiff will be 151 as expected 
var actualDaysDiff = (finish - start).TotalDays; 
// using the new method newDaysDiff will be 150 
int newDaysDiff = ((360 * (finish.Year - start.Year)) + (30 * (finish.Month - start.Month)) + (d2 - d1)); 

我得到您的其他例子正确的结果(其中,我认为,应该是181天)。

有关此主题的检查的详细信息如下:

  1. 360-day calendar
  2. C# for Financial Markets
相关问题