/// <summary>
/// 检验日期格式是否正确
/// </summary>
public string IsDateFormat(string strDate)
{
Regex r1 = new Regex(@"^(?<year>[1-9][0-9]{0,3})/(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})$");
Regex r2 = new Regex(@"^(?<year>[1-9][0-9]{0,3})-(?<month>[0-9]{1,2})-(?<day>[0-9]{1,2})$");
Regex r3 = new Regex(@"^(?<year>[1-9][0-9]{0,3})年(?<month>[0-9]{1,2})月(?<day>[0-9]{1,2})日$");
Regex r4 = new Regex(@"^(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})/(?<year>[1-9][0-9]{0,3})$");
// 取得日期的年,月,日
string year, month, date;
if(Regex.IsMatch(strDate,@"^(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})/(?<year>[1-9][0-9]{3})$"))
{
year = r4.Match(strDate).Result("${year}");
month = r4.Match(strDate).Result("${month}");
date = r4.Match(strDate).Result("${day}");
}
else if (Regex.IsMatch(strDate,@"^(?<year>[1-9][0-9]{0,3})/(?<month>[0-9]{1,2})/(?<day>[0-9]{1,2})$"))
{
year = r1.Match(strDate).Result("${year}");
month = r1.Match(strDate).Result("${month}");
date = r1.Match(strDate).Result("${day}");
}
else if(Regex.IsMatch(strDate,@"^(?<year>[1-9][0-9]{0,3})-(?<month>[0-9]{1,2})-(?<day>[0-9]{1,2})$"))
{
year = r2.Match(strDate).Result("${year}");
month = r2.Match(strDate).Result("${month}");
date = r2.Match(strDate).Result("${day}");
}
else if(Regex.IsMatch(strDate,@"^(?<year>[1-9][0-9]{0,3})年(?<month>[0-9]{1,2})月(?<day>[0-9]{1,2})日$"))
{
year = r3.Match(strDate).Result("${year}");
month = r3.Match(strDate).Result("${month}");
date = r3.Match(strDate).Result("${day}");
}
else
{
return "error";
}
// 最后检查日期的正确性
try
{
System.DateTime dt = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(date));
return dt.ToString("yyyy-MM-dd");
}
catch
{
return "error";
}
}
正则表达式,初看就让人生畏,只要坚持 :rolleyes:
另外还是觉本代码不是很完美,代码有些多,但一时也想不到好的方法。
最后一段new DateTime的方法,是.net固有的方法,尝试建立日期格式,如能建立,说明输入是正确的,不能就返回"ERROR"。
;)当然,你也可以用自己方法去验证年份正确性,如2月29日是否正确等问题。但我是不会再去做这样的事了,别人已经做得很完美了,就省下这时间去做些更有意义的事了。 |