0

I want my program to validate that the date format is mm/dd/yyyy. I don't want to use any throw/catch blocks.

class FunWithScheduling
{
    public void AddView()
    {
        ...
        ...

        Console.WriteLine("Enter the Date Scheduled For the Meeting:");
        string Date = Console.ReadLine();
        DateTime date = DateTime.Parse(Date);
        string formatted = date.ToString("MM-dd-yyyy");
        if (Date != formatted)
            Console.WriteLine("Invalid Choice");

        ...
        ...
    }

    static void Main()
    {
        FunWithScheduling a = new FunWithScheduling();
        a.AddView();
    }
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Ruckus Maker
  • 25
  • 1
  • 6

3 Answers3

1

Try:

DateTime dt;
if (
    DateTime.TryParseExact(
        "08/03/2013", 
        "MM/dd/yyyy", 
        null, 
        System.Globalization.DateTimeStyles.None, 
        out dt
    )
)
{
    //Date in correct format
}
Kees
  • 1,408
  • 1
  • 15
  • 27
1

Check out DateTime.TryParseExact

Frode
  • 3,325
  • 1
  • 22
  • 32
1

you need to change this line

 DateTime date = DateTime.Parse(Date);

To

DateTime date;
if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"), 
                          DateTimeStyles.None, 
                          out date))
 {
    Console.WriteLine("Invalid Choice");
 }
Ehsan
  • 31,833
  • 6
  • 56
  • 65