user5462581
user5462581

Reputation: 159

C# Check if input is valid date

I am working on a calendar. And here I want to check if the users input is a date and if it's not showing an error. I heard about DateTime.TryParse. How can I use this here properly? Can maybe anyone explain it in simple words?

    public void addMeeting()
    {
      string readAddMeeting;
      var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this

      Console.WriteLine("Add a schedule for specific dates: ");

      readAddMeeting = Console.ReadLine();
    }

Upvotes: 2

Views: 14451

Answers (2)

Thomas
Thomas

Reputation: 2984

Even if it sounds a bit brutal, but it seems ike you should do some readup on arrays/lists, foreach loops and DateTime.TryParse.

That aside you have different possible date formats and want to see if one of them is valid. If we take the example from the msdn homepage for tryparse https://msdn.microsoft.com/en-us/library/ch92fbc1(v=vs.110).aspx and use foreach it becomes quite easy:

public void addMeeting()
{
    string readAddMeeting;
    var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; // I copied this
    bool isDateOk = false;

    Console.WriteLine("Add a schedule for specific dates: ");

    readAddMeeting = Console.ReadLine();

    foreach (string myDateFormat in dateFormats)
    {
        DateTime dateValue;
        if (DateTime.TryParse(readAddMeeting, dateValue)) 
        {
            isDateOk = true;
        }
    }

    if (isDateOk == false)
    {
        Console.Writeline("Sorry this is not a valid date");
    }
}

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460098

Use DateTime.TryParseExact in this way:

public void addMeeting()
{
    var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}; 
    Console.WriteLine("Add a schedule for specific dates: ");
    string readAddMeeting = Console.ReadLine();
    DateTime scheduleDate;
    bool validDate = DateTime.TryParseExact(
        readAddMeeting,
        dateFormats,
        DateTimeFormatInfo.InvariantInfo,
        DateTimeStyles.None, 
        out scheduleDate);
    if(validDate)
        Console.WriteLine("That's a valid schedule-date: {0}", scheduleDate.ToShortDateString());
    else
        Console.WriteLine("Not a valid date: {0}", readAddMeeting);
}

The method returns a bool indicating whether it could be parsed or not and you pass a DateTime variable as out parameter which will be initialized if the date was valid.

Note that i'm using DateTimeFormatInfo.InvariantInfo because you don't want to use the local DateTime format but one that works in any culture. Otherwise the / in dd/MM/yyyy would be replaced with your current culture's date separators. Read

Upvotes: 8

Related Questions