C# Check if input is valid date

11,097

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

Share:
11,097
user5462581
Author by

user5462581

Updated on August 29, 2022

Comments

  • user5462581
    user5462581 over 1 year

    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();
        }