'CDay.vb
' Encapsulates month, day and year.

    Imports System.Windows.Forms

Class CDay
    Inherits Object

    Private mMonth As Integer ' 1-12
    Private mDay As Integer ' 1-31 based on month
    Private mYear As Integer ' any year

    ' constructor confirms proper value for month, then calls
    ' method CheckDay to confirm proper value for day
    Public Sub New(ByVal monthValue As Integer, _
             ByVal dayValue As Integer, ByVal yearValue As Integer)

        ' ensure month value is valid
        If (monthValue > 0 AndAlso monthValue <= 12) Then
            mMonth = monthValue
        Else
            mMonth = 1

            ' inform user of error
            Dim errorMessage As String = _
                           "Month invalid. Set to month 1."

            MessageBox.Show(errorMessage, "", _
               MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If

        mYear = yearValue
        mDay = CheckDay(dayValue) ' validate day

    End Sub ' New
    ' confirm proper day value based on month and year
    Private Function CheckDay(ByVal testDayValue As Integer) _
             As Integer

        Dim daysPerMonth() As Integer = _
                    {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}

        If (testDayValue > 0 AndAlso _
           testDayValue <= daysPerMonth(mMonth)) Then

            Return testDayValue
        End If

        ' check for leap year in February
        If (mMonth = 2 AndAlso testDayValue = 29 AndAlso _
           mYear Mod 400 = 0 OrElse mYear Mod 4 = 0 AndAlso _
           mYear Mod 100 <> 0) Then

            Return testDayValue
        Else

            ' inform user of error
            Dim errorMessage As String = _
                           "day " & testDayValue & "invalid. Set to day 1. "

            MessageBox.Show(errorMessage, "", _
               MessageBoxButtons.OK, MessageBoxIcon.Error)

            Return 1 ' leave object in consistent state
        End If
    End Function ' CheckDay

    ' create string containing month/day/year format
    Public Function ToStandardString() As String
        Return mMonth & "/" & mDay & "/" & mYear
    End Function ' ToStandardString
End Class ' CDay

