用正则表达式检测日期时间
在 http://www.regexlib.com/ 找到一个用于日期时间检测的正则表达式, 效果不错.
/// <summary> /// 检测是否为可识别的日期时间格式 /// </summary> /// <param name="dateTime"></param> /// <returns></returns> internal static bool CheckDateTimeFormat(string dateTime) { string datePattern = @"^(((((0?\d)|(1[0-2]))\/(([0-1]?\d)|(2[0-8])))|(((0?[1,3-9])|(1[0-2]))\/29)|(((0?[1,3-9])|(1[0-2]))\/30)|(((0?[13578])|(1[0-2])))\/31)\/((19\d{2})|([2-9]\d{3}))|(0?2\/29\/(((([2468][048])|([3579][26]))00)|(((19)|([2-9]\d))(([2468]0)|([02468][48])|([13579][26]))))))$"; string dateTimePattern = @"^(((((0?\d)|(1[0-2]))\/(([0-1]?\d)|(2[0-8])))|(((0?[1,3-9])|(1[0-2]))\/29)|(((0?[1,3-9])|(1[0-2]))\/30)|(((0?[13578])|(1[0-2])))\/31)\/((19\d{2})|([2-9]\d{3}))|(0?2\/29\/(((([2468][048])|([3579][26]))00)|(((19)|([2-9]\d))(([2468]0)|([02468][48])|([13579][26]))))))\s(([01]?\d)|(2[0-3]))(:[0-5]?\d){2}$"; return Regex.IsMatch(dateTime, datePattern) || Regex.IsMatch(dateTime, dateTimePattern); }
匹配: 02/29/2004 02/29/2004 15:02:59 2/29/2004 15:2:59
不匹配: 2/29/1900 2/29/1900 25:12:59