YYYYMMDD日期格式正规防爆pression验证用C#.net的日期日期、正规、格式、YYYYMMDD

由网友(七张试卷散了这个夏天)分享简介:我需要经常使用前pression在C#中验证日期格式。I need to validate the date format using regular expression in C#.下面是格式为:年月日 推荐答案普通EX pressions不适合这项任务。这是困难的例子,写一个正EX pression相匹配...

我需要经常使用前pression在C#中验证日期格式。

I need to validate the date format using regular expression in C#.

下面是格式为:年月日

推荐答案

普通EX pressions不适合这项任务。这是困难的例子,写一个正EX pression相匹配的有效日期20080229,而不是无效的日期20100229。

Regular expressions aren't suitable for this task. It is difficult for example to write a regular expression that matches the valid date "20080229" but not the invalid date "20100229".

相反,你应该使用 DateTime.TryParseExact 与格式字符串年月日。下面是一个例子:

Instead you should use DateTime.TryParseExact with the format string "yyyyMMdd". Here is an example:

string s = "20100229";
DateTime result;
if (!DateTime.TryParseExact(
     s,
     "yyyyMMdd",
     CultureInfo.InvariantCulture,
     DateTimeStyles.AssumeUniversal,
     out result))
{
    Console.WriteLine("Invalid date entered.");
};
阅读全文

相关推荐

最新文章