Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YYYYMMDD Date Format regular Expression to validate a date in C# .net

Tags:

c#

.net

regex

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

Here is the format: "YYYYMMDD"

like image 228
VInayK Avatar asked Jan 22 '11 08:01

VInayK


3 Answers

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.");
};
like image 82
Mark Byers Avatar answered Oct 27 '22 00:10

Mark Byers


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.

like image 28
Michael Connor Avatar answered Oct 26 '22 22:10

Michael Connor


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   
}
like image 40
tenor Avatar answered Oct 26 '22 22:10

tenor