C#驗證給定的字符串形式的日期是否合法
這段C#代碼用于驗證日期的有效性,對于用戶輸入的不規則日期也作了簡單處理,比如用戶輸入了“今天”,則代碼會認為用戶要返回的是今天的日期,另外可以對純數字的日期進行解析,比如:20130906
/// <summary> /// 驗證日期是否合法,對不規則的作了簡單處理 /// </summary> /// <param name="date">日期</param> 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 { //如果日期字符串中存在非數字,則返回false if (!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; } #endregion return false; } }</pre>
本文由用戶 fdwm 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!