How to validate DateTime format?

前端 未结 7 1814
广开言路
广开言路 2020-12-11 00:53

I am suppose to let the user enter a DateTime format, but I need to validate it to check if it is acceptable. The user might enter \"yyyy-MM-dd\" and it would be fine, but t

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 01:23

    Are you looking for something like this?

    DateTime expectedDate;
    if (!DateTime.TryParse("07/27/2012", out expectedDate))
    {
        Console.Write("Luke I am not your datetime.... NOOO!!!!!!!!!!!!!!");
    }
    

    If your user knows the exact format(s) needed...

    string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" };
    DateTime expectedDate;
    if (!DateTime.TryParseExact("07/27/2012", formats, new CultureInfo("en-US"), 
                                DateTimeStyles.None, out expectedDate))
    {
        Console.Write("Thank you Mario, but the DateTime is in another format.");
    }
    

提交回复
热议问题