Arrays in Visual Basic

The next program will use an array with the number of days in each month. When a date is selected from the DateTimePickerdatetimepicker , we calculate and display the day of the year. This is done by starting with the day of the month, then add the number of days in each previous month. For example if the date selected is May 21, we would start with a total of 21, then add the number of days in January, February, March, and April. One little problem is leap year. We use a function called IsDate and test if 2/29 is a date for the year selected. If so, we set the number of days in February to 29, otherwise it is 28.

  1. Start a new Windows application and name it Julian. Add a DateTimePicker datetimepicker, control to the form. (It will be named DateTimePicker1.)
  2. Write the code as shown below:
'Julian Date
Public Class Form1
    'Programmer: Janet Joy
    Dim Days() As Integer = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        'Date is picked by user
        Dim Month As Integer = DateTimePicker1.Value.Month
        Dim Julian As Integer = DateTimePicker1.Value.Day
        'start with Julian is the day, then add number of days in each previous month
        Dim Year As Integer = DateTimePicker1.Value.Year
        'If Febraury 29 is valid date, it is leap year: Feb. has 29 days
        If IsDate("2/29/" & Year) Then Days(2) = 29 Else Days(2) = 28
        Dim M As Integer
        For M = 1 To Month - 1
            Julian = Julian + Days(M) 'Add number of days in each month
        Next M
        Me.Text = "Day " & Julian
    End Sub
End Class

Experiment: Add an array with the names of the months in Spanish or some other language. When a date is selected display the name of the month in the other language.

Experiment: Using the IsDate function and a loop print a list of all years that were leap years from 1900 to the present.

NEXT: ReDim: Change the Size of the Array