minimal_
minimal_

Reputation: 29

Validating DateTime Input from Console in C#

In a bid to learn C# in a hands-on manner, I started working through these assignments I found online...

http://www1.cs.columbia.edu/~lok/csharp/assignments.html

I am stuck on Exercise 1, Question 3. How can I request a date from the console and then check against given criteria? In this case, check if the date is after today and provide an 'invalid' message if true.

My code currently looks like the below. I feel like the logic is there, but something to do with scope won't let it compile - the userBirthdate seems inaccessible outside of the loop.

I'm sure there's also a much simpler solution.

Any help greatly appreciated - thanks guys!

        //Set today's date as a variable            
        DateTime todayDate = DateTime.Today;
        DateTime userBirthdate;

        //Ask user for birth date
        Console.Write("Please enter your date of birth (dd/mm/yy):  ");

        //Validate the input and set as a variable
        bool inputValid = false;
        while (inputValid != true)
        {
            if (DateTime.Parse(Console.ReadLine()) > todayDate)
            {
                Console.Write("Invalid Date.  Please enter your date of birth (dd/mm/yy):  ");
            }
            else
            {
                userBirthdate = DateTime.Parse(Console.ReadLine());
                Console.WriteLine(userBirthdate);
                inputValid = true;
            }
        }

        //Calculate user age
        int userAge = todayDate.Year - userBirthdate.Year;
        if (userBirthdate > todayDate.AddYears(-userAge)) userAge--;

        //Output
        Console.WriteLine("You are {0} years old!", userAge);
        Console.ReadLine();

Upvotes: 0

Views: 4901

Answers (4)

DavidG
DavidG

Reputation: 118977

As you are not initialising the variable userBirthdate, the compiler is giving you a warning when you try to use it later. Set it to a value first or change your logic:

DateTime userBirthdate = DateTime.Today;

Upvotes: 0

AD.Net
AD.Net

Reputation: 13399

Few things (also initliaze the userBirthDate as pointed out in other posts:

  1. Use DateTime.TryParse(Console.ReadLine(), out userBirthdate) to see if it's a valid DateTime. If you do this right away you might not even need to initialize userBirthdate
  2. Check if it's > DateTime.Now to make sure it's not in future.
  3. Do use the Subtract method to see if it's too long ago in the past. It gives you a TimeSpan object which you can use to make sure it's not very old like 135 years or so.

Upvotes: 1

Connor
Connor

Reputation: 81

In addition to the other answers, you're calling Console.ReadLine() twice: once when you read to check and validate that the input isn't greater than today's date and again when assigning it to userBirthdate. You should assign it first and then do validation, otherwise, your program will hang because it is waiting for more input from the user.

while (inputValid != true)
{ 
    userBirthdate = DateTime.Parse(Console.ReadLine());

    if (userBirthdate > todayDate)
    {
        Console.Write("Invalid Date.  Please enter your date of birth (dd/mm/yy):  ");
    }
    else
    {
        Console.WriteLine(userBirthdate);
        inputValid = true;
    }
}

Upvotes: 0

D Stanley
D Stanley

Reputation: 152566

You need to initialize userBirthdate outside of the loop:

    DateTime userBirthdate = DateTime.MinValue;

The value doesn't matter since you're going to assign it a value within the while loop, but the compiler can't determine that without doing more static analysis than it's designed for.

There are several other issues, but that should solve the compilation problem.

Upvotes: 0

Related Questions