用于验证日期的有效性,对于用户输入的不规则日期也作了简单处理,比如用户输入了“今天”,则代码会认为用户要返回的是今天的日期,另外可以对纯数字的日期进行解析,比如:20130906
////// 验证日期是否合法,对不规则的作了简单处理/// /// 日期public static bool IsDate(ref string date){//如果为空,认为验证合格if (IsNullOrEmpty(date)){return true;}//清除要验证字符串中的空格date = date.Trim();//替换\date = date.Replace(@"\", "-");//替换/date = date.Replace(@"/", "-");//如果查找到汉字"今",则认为是当前日期if (date.IndexOf("今") != -1){date = DateTime.Now.ToString();}try{//用转换测试是否为规则的日期字符date = Convert.ToDateTime(date).ToString("d");return true;}catch{//如果日期字符串中存在非数字,则返回falseif (!IsInt(date)){return false;}#region 对纯数字进行解析//对8位纯数字进行解析if (date.Length == 8){//获取年月日string year = date.Substring(0, 4);string month = date.Substring(4, 2);string day = date.Substring(6, 2);//验证合法性if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100){return false;}if (Convert.ToInt32(month) > 12 || Convert.ToInt32(day) > 31){return false;}//拼接日期date = Convert.ToDateTime(year + "-" + month + "-" + day).ToString("d");return true;}//对6位纯数字进行解析if (date.Length == 6){//获取年月string year = date.Substring(0, 4);string month = date.Substring(4, 2);//验证合法性if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100){return false;}if (Convert.ToInt32(month) > 12){return false;}//拼接日期date = Convert.ToDateTime(year + "-" + month).ToString("d");return true;}//对5位纯数字进行解析if (date.Length == 5){//获取年月string year = date.Substring(0, 4);string month = date.Substring(4, 1);//验证合法性if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100){return false;}//拼接日期date = year + "-" + month;return true;}//对4位纯数字进行解析if (date.Length == 4){//获取年string year = date.Substring(0, 4);//验证合法性if (Convert.ToInt32(year) < 1900 || Convert.ToInt32(year) > 2100){return false;}//拼接日期date = Convert.ToDateTime(year).ToString("d");return true;}#endregionreturn false;}}