Day360 in vb.net

I want to use the Days360 function in VB.Net. I need to know the difference in days between two dates assuming 360 days in a year (not 365 days the DateDiff function uses).

For example DateDiff(DateInterval.Day,"16/10/2015", "04/02/2016") = 111 days, but Days360 should return 109 days.

Upvotes: 1

Views: 1163

Answers (1)

Blackwood
Blackwood

Reputation: 4534

Days360 function in Excel calculates the days between two dates using a fictional calendar that has 30 days in each month. This method is used for some financial purposes.

You can write a function to do the same calculation.

[Edit]
Excel supports two versions of the calculation: one common in the US (this is the default) and the other common in Europe (see the documentation of the DAYS360 function for details).

The code I originally posted implemented the European version. I have updated it to support both versions. Thanks to Nikhil Vartak for pointing this out.

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

Upvotes: 3

Related Questions