如何将日期添加到数组?

时间:2019-03-26 12:02:29

标签: vb.net

我想将日期添加到给定开始日期和结束日期的数组中。

我已经尝试过将其声明为Array和ArrayList,但是在同一行给出了相同的错误。这是示例代码:

Dim startP As DateTime = New DateTime(2019, 3, 27)
Dim endP As DateTime = New DateTime(2019, 3, 30)
Dim CurrD As DateTime = startP
Dim DateArray As ArrayList

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    While (CurrD <= endP)
        DateArray.Add(CurrD)
        CurrD = CurrD.AddDays(1)
    End While
End Sub

两个都给出了错误“未处理NullReferenceException”

3 个答案:

答案 0 :(得分:1)

由于未初始化DateArray.,您会遇到错误:

Dim DateArray As New ArrayList

答案 1 :(得分:1)

列表可能是一个更好的选择。请注意示例中的列表是如何初始化的。

Dim startP As DateTime = New DateTime(2019, 3, 27)
Dim endP As DateTime = New DateTime(2019, 3, 30)
Dim CurrD As DateTime = startP
Dim DateArray As New List(Of DateTime)

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    While (CurrD <= endP)
        DateArray.Add(CurrD)
        CurrD = CurrD.AddDays(1)
    End While
    'where you need an array of DateTime do
    '   DateArray.ToArray
End Sub

答案 2 :(得分:0)

您可以执行以下操作。

  Dim date_array As New List(Of Date)
  date_array.Add(New Date()) ' add as much as you want in a loop or manually
  date_array.ToArray() ' to return an array of dates..