i had the below code to get list the months between two dates
but my problem i did not get the last day from the month
for example : Date1: 31/10/2017 Date2: 31/3/2018
my Result :
31-10-2017
30-11-2017
30-12-2017
30-1-2017
28-2-2018
28-3-2018
it's should be
31-10-2017
30-11-2017
31-12-2017
31-1-2017
28-2-2018
31-3-2018
Dim startDay As Date = StartDate.SelectedDate
Dim endDay As Date = EndDate.SelectedDate
Dim dayCtr As Date
dayCtr = startDay
Do While (dayCtr <= endDay)
' MsgBox(dayCtr.Date.Day & "-" & dayCtr.Date.DayOfWeek.ToString())
ListBox1.Items.Add(dayCtr.Date.Day & "-" & dayCtr.Date.Month.ToString() & "-" & dayCtr.Date.Year.ToString())
dayCtr = dayCtr.AddMonths(1)
Loop
AddMonth(1) adds 1 to the month component of the date (and kindly wraps around to the next year so you don't have to do that) but the rest is up to you.
Private Function GetLastDayOfMonth(currentDate As Date) As Date
Dim result As Date
'Jump one Month ahead
result = currentDate.AddMonths(1)
'Go to first day of that Month
result = New Date(result.Year, result.Month, 1)
'Go one day back
result = result.AddDays(-1)
Return result
End Function
Use this function in your code like so:
Dim startDay As Date = StartDate.SelectedDate
Dim endDay As Date = EndDate.SelectedDate
Dim dayCtr As Date
dayCtr = startDay
Do While (dayCtr <= endDay)
' MsgBox(dayCtr.Date.Day & "-" & dayCtr.Date.DayOfWeek.ToString())
Dim lastDay As Date = GetLastDayOfMonth(dayCtr)
ListBox1.Items.Add(lastDay.Date.Day & "-" & lastDay.Date.Month.ToString() & "-" & lastDay.Date.Year.ToString())
dayCtr = dayCtr.AddMonths(1)
Loop
and you should be fine. .NET helps you A LOT with handling dates but a little elbow grease is still needed.