Validating a date format string in c#

一个人想着一个人 提交于 2019-12-08 05:54:10

问题


I want users to be able to enter a date format string in a text box so they can specify how they want a date value to be Displayed in their windows form

How can I validate this date format string entered in a text box so that they can enter only a valid C# Date format


回答1:


For a valid date, you need date (dd), month (mm) and year(yyyy). I can give you a simple regex, for validating dates like dd/mm/yy or dd.mm/yyyy

(dd|mm|yy{2,4}?).(dd|mm||yy{2,4}?).(dd|mm||yy{2,4}?)

It passes for any combination of dd,mm and yyyy or yy.

It also accepts dd.dd.mm or anything like that. So, Make sure you check for multiple occurrences of characters.




回答2:


You can use DateTime.TryParse and check whether the entered date time string is valid or not.

Here is the code:

DateTime dt;
string myDate = "2016-12-10";
bool success = DateTime.TryParse(myDate, out dt);
Console.WriteLine(success);

Console.WriteLine(DateTime.TryParse("2016-12-10", out dt));    //true
Console.WriteLine(DateTime.TryParse("10-12-2016", out dt));    //true
Console.WriteLine(DateTime.TryParse("2016 July, 01", out dt));    //true
Console.WriteLine(DateTime.TryParse("July 2016 99", out dt));    //true


来源:https://stackoverflow.com/questions/40924767/validating-a-date-format-string-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!