C#检查输入是否为有效日期

use*_*581 0 c# time date

我正在制作日历.在这里,我想检查用户输入是否是一个日期,如果它没有显示错误.我听说过DateTime.TryParse.我怎么能在这里正确使用它?也许有人可以用简单的话来解释它吗?

    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();
    }
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 7

DateTime.TryParseExact以这种方式使用:

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);
}
Run Code Online (Sandbox Code Playgroud)

该方法返回一个bool指示是否可以解析的方法,并将一个DateTime变量作为out参数传递,如果日期有效,该参数将被初始化.

请注意,我正在使用,DateTimeFormatInfo.InvariantInfo因为您不想使用本地DateTime格式,而是使用适用于任何文化的格式.否则,/in dd/MM/yyyy将替换为您当前文化的日期分隔符.