Home
Manage Your Code
Snippet: isValidDateTime (C#)
Title: isValidDateTime Language: C#
Description: Is a string a valid Datetime. Views: 471
Author: Rich Krueger Date Added: 10/28/2007
Copy Code  
1  public static bool isValidDateTime(string str)
2  {
3    System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^([0]?[1-9]|[1][0-2])[/-]([0]?[1-9]|[1-2][0-9]|3[0-1])[/-](200[0-9])(((\x20)([0]?[1-9]|[1][0-2]):[0-5][0-9]:[0-5][0-9](\x20)?(am|AM|pm|PM))?)$");
4
5
6    if (!reg.Match(str).Success)
7    {
8      return false;
9    }
10
11    try
12    {
13      DateTime dt = Convert.ToDateTime(str);
14      return true;
15    }
16    catch
17    {
18      return false;
19    }
20  }
21