YYYYMMDD日期格式正规防爆pression验证用C#.net的日期 [英] YYYYMMDD Date Format regular Expression to validate a date in C# .net

查看:164
本文介绍了YYYYMMDD日期格式正规防爆pression验证用C#.net的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要经常使用前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.");
};

这篇关于YYYYMMDD日期格式正规防爆pression验证用C#.net的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆