vb.net 360 天

Day360 in vb.net

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

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

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