Link to home
Start Free TrialLog in
Avatar of aclaus225
aclaus225

asked on

Creating a Date Checker in Visual Basic

Greetings to you.

I have been tasked with creating a date checker in Visual Basic.  I am not really that familiar with Visual Basic, but I am thinking that I want to create it so that it checks the month, day, and year independently of each other.  I also think that in checking months it should say something like
If month=1 then day can be 1-31
Else If month=2 then day can be 1-28, but do not know how to do leap year then.  

Can anyone help me out with this?
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

What do you mean date checker ?

Why not attempt to create a Date object based on the inputted year, month, day then check that the entered year/month/day values are those in the date object.  If they aren't then it isn't a valid year/month/day combination that was entered.
Avatar of Rgonzo1971
Rgonzo1971

Hi,

Why not use the Isdate function?

Regards
Avatar of aclaus225

ASKER

Rgonzo and Andy,

This is actually an assignment that requires me to not use any built in date routines or functions.  I do not quite know what that means, but I was thinking that I could do it the way that I had said: If the month entered is 1 and the date is anywhere between 1 and 31 then say that it is valid.  Is there not a way to do that in Visual Basic?  

Andy,
How would I actually create the date object like you said?
Unless this is for a homework assignment, nobody does manual checking of dates like that.

As suggested, you can use IsDate() or DateTime.TryParse() to see if the values together comprise a valid date.

"... but do not know how to do leap year ..."

If you're really set on doing it manually, then see the "Algorithm" section here:
http://en.wikipedia.org/wiki/Leap_year
Idle,

This is a homework assignment.  I read through the book and do not see things like my mind produces, so I am wondering if it is at all possible to do the manual checking like I am asking.
The following will tell you if year 'n' is a leap year
DateTime.IsLeapYear(n)

So everything else is just checking in a case statement - no functions or inbuilt classes in use.
Thanks for this Andy.
...I think that violates your rule:

    "This is actually an assignment that requires me to not use any built in date routines or functions."

See the wiki page I linked on how to manually determine if a year is a leap year.
Is this a Console app or a WinForms app?
Here's something to get you started and give you some ideas...
Public Class Form1

    Private Sub btnCheckDate_Click(sender As System.Object, e As System.EventArgs) Handles btnCheckDate.Click
        Dim month, day, year As Integer
        If Integer.TryParse(txtMonth.Text, month) Then
            If Integer.TryParse(txtDay.Text, day) Then
                If Integer.TryParse(txtYear.Text, year) Then
                    If IsValidDate(month, day, year) Then
                        MessageBox.Show("The Date is Valid!")
                    Else
                        MessageBox.Show("Invalide Date!")
                    End If
                Else
                    MessageBox.Show("Enter a Valid Year", "Invalid Year")
                End If
            Else
                MessageBox.Show("Enter a Valid Day", "Invalid Day")
            End If
        Else
            MessageBox.Show("Enter a Valid Month", "Invalid Month")
        End If
    End Sub

    Private Function IsValidDate(ByVal month As Integer, ByVal day As Integer, ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        If month <= 0 OrElse day <= 0 OrElse year <= 0 Then
            validDate = False
        Else

            ' ... fill in code here ...

        End If

        Return validDate
    End Function

    Private Function IsLeapYear(ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        ' ... fill in code here ...

        Return validDate
    End Function

End Class

Open in new window

This would be a WinForms app.  

I am told that I need to use a KeyPress event to restrict entry into a text box where I want the format to be mm/dd/yy, so I am thinking that that means I need to do this:

Private Sub EntryBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles EntryBox.KeyPress

        e.Handled = True

        If IsNumeric(e.KeyChar) Then

        Or e.KeyChar = "." _

        Or e.KeyChar = "," Then

            e.Handled = False

        End If

    End Sub

Open in new window


But this comes up with a Syntax error saying I can't use Or.  
As for coding:
1.            Take in a string from the user in the textbox (would this just involve a pure
EntryBox.Text = EntryBox.ToString("mm/dd/yy") or am I incorrect? )

2.            Use string functions  to cut the string into pieces (day, month, year)
I have no idea how to do this.  

3.            Attempt to convert the string pieces into numbers
(I think this involves EntryBox.Text to Int32)

4.            Test the numbers for valid ranges for days, months and years
This is what I originally wrote about, trying to figure out how to write an algorithm that would say if month is 1 then you can have a range between 1 and 30.  

5.            Test the numbers for validity given the other numbers values (no more than 30 days in November)

6.            Test the leap year situation
If you want to restrict the box to numeric digits and forward slash:
    Private Sub EntryBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles EntryBox.KeyPress
        If Not IsNumeric(e.KeyChar) AndAlso e.KeyChar <> "/" Then
            e.Handled = True
        End If
    End Sub

Open in new window

Thanks for that help Idle.  I am a very slow learner when it comes to Visual Basic, I suppose.
I got the string to cut by doing this:
 Dim converted() As String
        converted = EntryBox.Text.Split(CChar("/"))

Open in new window

But now that I have this split how do I actually get the program to read the individual numbers that it just split.  I can get a message box to display 02, then 28, then 13, but how do I get Visual Basic to actually see that first one as a month, the second one as a date, and the third one as a year?
You could assign each array element to a locally declared variable:

    If converted.GetUpperBound(0) >=2 Then
        Dim strMonth As String = converted(0)
        Dim strDay As String = converted(1)
        Dim strYear As String = converted(2)

        ' ... now attempt to convert the string values to integers with Integer.TryParse()...

    End If

*See my previous post for how to use Integer.TryParse().
Alright, now I have this:
Private Sub CheckDateButton_Click(sender As System.Object, e As System.EventArgs) Handles CheckDateButton.Click
        'Split the input in the text box into mm/dd/yy format
        Dim converted() As String
        Dim Month, Day, Year As Integer
        converted = EntryBox.Text.Split(CChar("/"))

        'Convert Into Usable Data
        If converted.GetUpperBound(0) >= 2 Then
            Dim mm As String = converted(0)
            Dim dd As String = converted(1)
            Dim yy As String = converted(2)
        End If


        If Integer.TryParse(converted(0), Month) Then
            If Integer.TryParse(converted(1), Day) Then
                If Integer.TryParse(converted(2), Year) Then
                    If IsValidDate(Month, Day, Year) Then
                        MessageBox.Show("The Date is Valid!")
                    Else
                        MessageBox.Show("Invalid Date!")
                    End If
                Else
                    MessageBox.Show("Enter a Valid Year", "Invalid Year")
                End If
            Else
                MessageBox.Show("Enter a Valid Day", "Invalid Day")
            End If
        Else
            MessageBox.Show("Enter a Valid Month", "Invalid Month")
        End If
    End Sub

Open in new window


But the only date that is invalid is 00/00/00.  I even put in 12/32/99 and it came back valid.
Did you put any code INSIDE the IsValidDate() function?...   =)

Also, since you're using converted directly in Integer.TryParse(), just get rid of the String variables:
    Private Sub CheckDateButton_Click(sender As System.Object, e As System.EventArgs) Handles CheckDateButton.Click
        Dim Month, Day, Year As Integer

        'Split the input in the text box into mm/dd/yy format
        Dim converted() As String = EntryBox.Text.Split(CChar("/"))

        'Convert Into Usable Data
        If converted.Length = 3 Then
            If Integer.TryParse(converted(0), Month) Then
                If Integer.TryParse(converted(1), Day) Then
                    If Integer.TryParse(converted(2), Year) Then
                        If IsValidDate(Month, Day, Year) Then
                            MessageBox.Show("The Date is Valid!")
                        Else
                            MessageBox.Show("Invalid Date!")
                        End If
                    Else
                        MessageBox.Show("Enter a Valid Year", "Invalid Year")
                    End If
                Else
                    MessageBox.Show("Enter a Valid Day", "Invalid Day")
                End If
            Else
                MessageBox.Show("Enter a Valid Month", "Invalid Month")
            End If
        Else
            MessageBox.Show("Invalid Format for Date!")
        End If
    End Sub

Open in new window

Got the date to be between certain range
Private Function IsValidDate(ByVal month As Integer, ByVal day As Integer, ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        If month >= 1 AndAlso month <= 12 OrElse day >= 1 AndAlso day <= 31 OrElse year <= 0 Then
            validDate = False
        Else

            ' ... fill in code here ...

        End If

        Return validDate
    End Function

Open in new window


But is there an easy way to specify if month is 1, 3, 5, 7, 8, 10, 12 then days should be between 1-31?
Private Sub CheckDateButton_Click(sender As System.Object, e As System.EventArgs) Handles CheckDateButton.Click
        'Split the input in the text box into mm/dd/yy format
        Dim Month, Day, Year As Integer

        'Split the input in the text box into mm/dd/yy format
        Dim converted() As String = EntryBox.Text.Split(CChar("/"))

        'Convert Into Usable Data
        If converted.Length = 3 Then
            If Integer.TryParse(converted(0), Month) Then
                If Integer.TryParse(converted(1), Day) Then
                    If Integer.TryParse(converted(2), Year) Then
                        If IsValidDate(Month, Day, Year) Then
                            MessageBox.Show("The Date is Valid!")
                        Else
                            MessageBox.Show("Invalid Date!")
                        End If
                    Else
                        MessageBox.Show("Enter a Valid Year", "Invalid Year")
                    End If
                Else
                    MessageBox.Show("Enter a Valid Day", "Invalid Day")
                End If
            Else
                MessageBox.Show("Enter a Valid Month", "Invalid Month")
            End If
        Else
            MessageBox.Show("Invalid Format for Date!")
        End If
    End Sub

    Private Function IsValidDate(ByVal month As Integer, ByVal day As Integer, ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        If month = 1 OrElse day >= 1 AndAlso day <= 31 OrElse year <= 0 Then
            validDate = False
        End If
        If month = 4, 6, 9, 11 OrElse day >= 1 AndAlso day <= 30 OrElse year <= 0 Then
            validDate = False

            ' ... fill in code here ...

        End If

        Return validDate
    End Function

    Private Function IsLeapYear(ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        ' ... fill in code here ...

        Return validDate
    End Function


End Class

Open in new window

Private Function IsValidDate(ByVal month As Integer, ByVal day As Integer, ByVal year As Integer) As Boolean
        Dim validDate As Boolean = True ' assume good until proven otherwise below

        If month = 1 OrElse day >= 1 AndAlso day <= 31 OrElse year <= 0 Then
            validDate = False
        End If
        If month = 4, 6, 9, 11 OrElse day >= 1 AndAlso day <= 30 OrElse year <= 0 Then
            validDate = False

            ' ... fill in code here ...

        End If

        Return validDate
    End Function

Open in new window


The first If statement with just 1 month works, but the second one does not.
I would use a Select Case statement like this:
    Private Function IsValidDate(ByVal month As Integer, ByVal day As Integer, ByVal year As Integer) As Boolean
        ' check for INVALID values first:
        If month < 0 OrElse month > 12 OrElse day < 0 OrElse year < 0 Then
            Return False ' immediately exit with false
        End If

        ' determine the max day for the given month:
        Dim maxDay As Integer = -1
        Select Case month
            Case 1, 3, 5, 7, 8, 10, 12
                maxDay = 31
            Case 2
                If IsLeapYear(year) Then
                    maxDay = 29
                Else
                    maxDay = 28
                End If
            Case 4, 6, 9, 11
                maxDay = 30
        End Select

        ' is the day valid for the month?
        If day <= maxDay Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function IsLeapYear(year As Integer) As Boolean
        Return ((year Mod 4 = 0) AndAlso (year Mod 100 <> 0) OrElse (year Mod 400 = 0))
    End Function

Open in new window

Idle, I really thank you for all your help.  It seems to be working really well and I wish I could award you actual money for all your help.  
As far as this solution goes, I want to be able to clear the text box after the user clicks OK on either "This Date is Valid" or "This Date Is Not Valid".  How do I do that?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Idle_Mind - don't forget that posting code for an assignment is against the EE rules.  ;-)
Agreed Andy...I did more showing than guiding in this one eh?...  =\