列出asp.net两个日期之间的月份

时间:2017-10-01 06:56:50

标签: asp.net vb.net

我有以下代码列出两个日期之间每个月的最后一天 但我的问题是我没有从这几个月的最后一天获得。

例如:Date1: 31/10/2017 Date2: 31/3/2018

我的结果:

31-10-2017
30-11-2017
30-12-2017
30-1-2017
28-2-2018
28-3-2018

应该是

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

感谢

2 个答案:

答案 0 :(得分:1)

AddMonth(1)在日期的月份组件中加1(并且好好包裹到下一年,所以你不必这样做)但其余的由你决定。

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

在您的代码中使用此功能,如下所示:

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

你应该没事。 .NET可以帮助您处理日期,但仍需要一点肘部油脂。

答案 1 :(得分:0)

在没有额外操作的情况下使用Date.DaysInMonth方法的投标方法很少

Private Iterator Function GetLastDatesFrom(startDate As Date, 
                                           endDate As Date) As IEnumerable(Of Date)
    Dim temp = startDate
    Do While (temp <= endDate)
        Dim lastDay = Date.DaysInMonth(temp.Year, temp.Month)
        Yield New Date(temp.Year, temp.Month, lastDay)

        temp = temp.AddMonths(1)
    Loop
End Function

然后

Dim startDay As Date = StartDate.SelectedDate
Dim endDay As Date = EndDate.SelectedDate

Dim dates = GetLastDatesFromRange(startDay, endDay).ToList()
ListBox1.Items.AddRange(dates)