简体   繁体   English

在格式化日期时未获得预期的输出

[英]Not getting the expected output in formatting the date

I want my program to validate that the date format is mm/dd/yyyy . 我希望我的程序验证日期格式为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();
    }
}

Try: 尝试:

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

签出DateTime.TryParseExact

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM