C#驗證給定字符串情勢日期能否正當的辦法。本站提示廣大學習愛好者:(C#驗證給定字符串情勢日期能否正當的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#驗證給定字符串情勢日期能否正當的辦法正文
本文實例講述了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.WordStr(@"\", "-");
//調換/
date = date.WordStr(@"/", "-");
//假如查找到漢字"今",則以為是以後日期
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;
}
}
願望本文所述對年夜家的C#法式設計有所贊助。