对于日期值的下一个循环

最后发布: 2016-02-12 04:49:55


问题

如何修复以下代码?

Dim xx As Date = New DateTime(2016, 1, 1)
Dim yy As Date = New DateTime(2016, 12, 31)
For ii = xx To yy
    MsgBox(ii)
Next ii

这是错误:

在此处输入图片说明

vb.net
回答

如错误消息所提示,您不能通过在日期上加1来增加日期。 假设您打算添加一天,则可以使用AddDays方法。

    Dim xx As Date = New DateTime(2016, 12, 29)
    Dim yy As Date = New DateTime(2016, 12, 31)
    Dim ii As Date = xx
    Do Until ii > yy
        MessageBox.Show(ii.ToShortDateString)
        ii = ii.AddDays(1)
    Loop


回答

您可以使用While循环:

While xx <= yy  
    MsgBox(xx)
    xx = xx.AddDays(1)  
End While

Enumerable.Range

Dim days = Enumerable.Range(0, Convert.ToInt32((yy-xx).TotalDays))
    .Select(Function(i) xx.AddDays(i))
For Each DateTime day in days
   MsgBox(day)
Next day

(这看起来很复杂,但是最好从描述数据而不是构建循环的角度出发进行思考)。

For循环:

Dim count = Convert.ToInt32((yy-xx).TotalDays)
For i As Integer To Count
    MsgBox(xx.AddDays(i))
Next i


回答

Dim xx As Date = New DateTime(2016, 1, 1)
Dim yy As Date = New DateTime(2016, 12, 31)

Dim intNumDays As Integer = CInt(Math.Ceiling((yy - xx).TotalDays))
For ii As Integer = 0 To intNumDays - 1
  MsgBox(xx.AddDays(ii))
Next ii