Checking Date format from a string in C#

2019-02-16 08:30发布

I want to check whether a string contains dates such as 1/01/2000 and 10/01/2000 in dd/MM/yyyy format.

So far I have tried this.

DateTime dDate = DateTime.Parse(inputString);
string.Format("{0:d/MM/yyyy}", dDate); 

But how can I check if that format is correct to throw an exception?

8条回答
Juvenile、少年°
2楼-- · 2019-02-16 09:26

Try this

DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate); 

see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

查看更多
smile是对你的礼貌
3楼-- · 2019-02-16 09:33

you can use DateTime.ParseExact with the format string

DateTime dt = DateTime.ParseExact(inputString, formatString, System.Globalization.CultureInfo.InvariantCulture);

Above will throw an exception if the given string not in given format.

use DateTime.TryParseExact if you don't need exception in case of format incorrect but you can check the return value of that method to identify whether parsing value success or not.

check Custom Date and Time Format Strings

查看更多
登录 后发表回答