0

我希望我的程序验证日期格式是否为mm/dd/yyyy. 我不想使用任何 throw/catch 块。

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

3 回答 3

1

你需要改变这一行

 DateTime date = DateTime.Parse(Date);

DateTime date;
if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"), 
                          DateTimeStyles.None, 
                          out date))
 {
    Console.WriteLine("Invalid Choice");
 }
于 2013-08-03T17:27:55.007 回答
1

尝试:

DateTime dt;
if (
    DateTime.TryParseExact(
        "08/03/2013", 
        "MM/dd/yyyy", 
        null, 
        System.Globalization.DateTimeStyles.None, 
        out dt
    )
)
{
    //Date in correct format
}
于 2013-08-03T17:22:13.970 回答
1

查看DateTime.TryParseExact

于 2013-08-03T17:22:17.443 回答