如何修复以下代码?
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
这是错误:
答案 0 :(得分:2)
如错误消息所示,您不能通过向其添加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
答案 1 :(得分:2)
您可以使用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
答案 2 :(得分:1)
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