Tuesday, June 07, 2005

Validating Date inputs for specific format.

There are times when we need to trap date input and see if the value is a valid date or not. the usual approach to this is to use DateTime.Parse and then trap exceptions. if there is an exception we assume that the date entered is not valid. however there are also times when we need to trap exact format in which the date entered. e.g. we want the user to enter 02-24-1995 5:00 and NOT 02/24/1995. The code snippet illustrates how this can be done.

System.Globalization.DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
dtFormat.LongDatePattern = "MM'-'dd'-'yyyy HH':'mm";
try
{
DateTime dt = DateTime.ParseExact("02-24-1995 5:00","MM'-'dd'-'yyyy HH':'mm", dtFormat);
}
catch(Exception ex)
{
MessageBox.Show("The Following Exception Was Trapped While Validating Date:" + ex.Message);
}

0 Comments:

Post a Comment

<< Home