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?
Visual Basic.NETVisual Basic ClassicVisual C++.NET

Avatar of undefined
Last Comment
Mike Tomlinson

8/22/2022 - Mon
AndyAinscow

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.
Rgonzo1971

Hi,

Why not use the Isdate function?

Regards
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?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Mike Tomlinson

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
aclaus225

ASKER
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.
AndyAinscow

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.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
aclaus225

ASKER
Thanks for this Andy.
Mike Tomlinson

...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.
Mike Tomlinson

Is this a Console app or a WinForms app?
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
Mike Tomlinson

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

aclaus225

ASKER
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
Mike Tomlinson

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

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
aclaus225

ASKER
Thanks for that help Idle.  I am a very slow learner when it comes to Visual Basic, I suppose.
aclaus225

ASKER
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?
Mike Tomlinson

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().
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
aclaus225

ASKER
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.
Mike Tomlinson

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

aclaus225

ASKER
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?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
aclaus225

ASKER
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

aclaus225

ASKER
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.
Mike Tomlinson

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

All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
aclaus225

ASKER
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
Mike Tomlinson

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
AndyAinscow

@Idle_Mind - don't forget that posting code for an assignment is against the EE rules.  ;-)
Mike Tomlinson

Agreed Andy...I did more showing than guiding in this one eh?...  =\
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.