YYYYMMDD Date Format regular Expression to validate a date in C# .net
I need to validate the date format using regular expression in C#.
Here is the format: "YYYYMMDD"
开发者_运维百科
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".
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.");
};
Ok, this is the most beautiful regex I've ever built. This accounts for all leap years since 1582, the introduction of leap. It also handles non leap every fourth century. For example, 1600 is leap but 1700 is not though it is divisible by four. I tested this on all days between 1582 and 9999.
var yyyymmdd = new RegExp("^(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}(?:(?:(?:09|04|06|11)(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02(?:[01][0-9]|2[0-8])))))$");
Another version using dashes
var yyyyDashMmDashDd = new RegExp("^(?:(?:(?:(?:(?:[13579][26]|[2468][048])00)|(?:[0-9]{2}(?:(?:[13579][26])|(?:[2468][048]|0[48]))))-(?:(?:(?:09|04|06|11)-(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)-(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02-(?:0[1-9]|1[0-9]|2[0-9]))))|(?:[0-9]{4}-(?:(?:(?:09|04|06|11)-(?:0[1-9]|1[0-9]|2[0-9]|30))|(?:(?:01|03|05|07|08|10|12)-(?:0[1-9]|1[0-9]|2[0-9]|3[01]))|(?:02-(?:[01][0-9]|2[0-8])))))$");
I love that this works for nearly all languages, as long as they support regex. While its arguably more sensible to use a language specific date parser, I thinks this shows the power and elegance of regular expressions.
Here is an image of the pattern with slashes in Regexper if you want to see it.
Consider using DateTime.TryParseExact to validate the date. You can use the method to silmultaneously validate and read the DateTime value.
For example:
DateTime dateValue;
if (DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
{
//Parsed Successfully
}
精彩评论