Link to home
Start Free TrialLog in
Avatar of iepaul
iepaulFlag for Ireland

asked on

calculate number of days in each month between two dates

How would I calculate the number of days in each month between two dates in vb.net?
Example: Given start date of 12/09/2010 and end date 07/11/2010 I would like to get back

09/2010 - 22 days
10/2010 - 31 days
11/2010 - 7 days

I am not to worried by the exact out format as long as I can distinguish between the months.

The start and end dates vary and could possibly be in the same month or across two months or even more.

Avatar of Zhaolai
Zhaolai
Flag of United States of America image

Try this (It works for me):


        Dim date1 As Date = #7/2/2010#
        Dim date2 As Date = #10/15/2010#
        Dim sMsg As String

        Dim iMonths As Integer = DateDiff(DateInterval.Month, date1, date2)
        If iMonths = 0 Then
            sMsg = date1.ToString("MM/yyyy") & " - " & DateDiff(DateInterval.Day, date1, date2) & " days"
            MessageBox.Show(sMsg)
        End If
        If iMonths = 1 Then
            sMsg = date1.ToString("MM/yyyy") & " - " & System.DateTime.DaysInMonth(date1.Year, date1.Month) - date1.Day & " days" & vbNewLine
            sMsg &= date2.ToString("MM/yyyy") & " - " & date2.Day & " days"
            MessageBox.Show(sMsg)
        End If
        If iMonths >= 2 Then
            sMsg = date1.ToString("MM/yyyy") & " - " & System.DateTime.DaysInMonth(date1.Year, date1.Month) - date1.Day & " days" & vbNewLine
            Dim newdate As Date = date1
            For i As Integer = 1 To iMonths - 1
                newdate = newdate.AddMonths(1)
                sMsg &= newdate.ToString("MM/yyyy") & " - " & System.DateTime.DaysInMonth(newdate.Year, newdate.Month) & " days" & vbNewLine
            Next
            sMsg &= date2.ToString("MM/yyyy") & " - " & date2.Day & " days"
            MessageBox.Show(sMsg)
        End If

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Zhaolai
Zhaolai
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Brad Brett
Avatar of iepaul

ASKER

great answer