vb.net中的第360天

时间:2016-02-04 22:12:45

标签: vb.net datediff

我想在VB.Net中使用Days360函数。假设一年中有360天(而不是DateDiff函数使用的365天),我需要知道两个日期之间的天数差异。

例如DateDiff(DateInterval.Day,"16/10/2015", "04/02/2016") = 111天,但Days360应返回109天。

1 个答案:

答案 0 :(得分:3)

Excel中的Days360功能使用每月30天的虚构日历计算两个日期之间的天数。此方法用于某些财务目的。

您可以编写一个函数来进行相同的计算。

<强> [编辑]
Excel支持两种版本的计算:一种在美国常见(这是默认值),另一种在欧洲常见(有关详细信息,请参阅documentation of the DAYS360 function)。

我最初发布的代码实现了欧洲版本。我已更新它以支持这两个版本。感谢Nikhil Vartak指出这一点。

Function Days360(startDate As DateTime, endDate As DateTime, euMethod As Boolean) As Integer
    Dim months As Integer = (endDate.Year - startDate.Year) * 12 + endDate.Month - startDate.Month

    If euMethod Then
        'Use European method (start or end dates after the 30th of the month are changed to 30th)
        Return months * 30 + Math.Min(30, endDate.Day) - Math.Min(30, startDate.Day)

    Else 'Use US method
        'If the start date is the last day of the month, change it to the 30th
        Dim startDay As Integer = startDate.Day
        startDay = If(startDate.Day >= DateTime.DaysInMonth(startDate.Year, startDate.Month), 30, startDate.Day)

        'If end date is last of the month, change it to the 30th
        Dim endDay As Integer = endDate.Day
        endDay = If(endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month), 30, endDate.Day)

        'If end date is last of the month and start date is before 30th, change end date to 1st of the next month
        If endDate.Day >= DateTime.DaysInMonth(endDate.Year, endDate.Month) And startDay < 30 Then
            endDay = 1
            months += 1
        End If

        Return months * 30 + endDay - startday
    End If
End Function