Monday, August 11, 2008

Elegant Date Validation in C#

Simple example of a clean, elegant way to validate a date of any format without throwing a single exception.


System.IFormatProvider format = new System.Globalization.CultureInfo("en-US", true);

DateTime outDate;

bool isDate = DateTime.TryParseExact("08112008", "MMddyyyy", format,
System.Globalization.DateTimeStyles.AllowWhiteSpaces, out outDate);

The TryParseExact method allows you specify the exact formatting of the input string. If the Parse is successful, the boolean returned will be True - and the output DateTime variable will contain a valid date.

0 comments:

Post a Comment