使用DateTime.TryParse
的問題在於它不支持非分隔符輸入日期的非常常見的數據輸入用例,例如, 011508
。
下面是一個如何支持它的例子。 (這是一個框架,我要建,所以它的簽名是有點怪異,但核心邏輯應該是可用的):
private static readonly Regex ShortDate = new Regex(@"^\d{6}$");
private static readonly Regex LongDate = new Regex(@"^\d{8}$");
public object Parse(object value, out string message)
{
msg = null;
string s = value.ToString().Trim();
if (s.Trim() == "")
{
return null;
}
else
{
if (ShortDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
}
if (LongDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
}
DateTime d = DateTime.MinValue;
if (DateTime.TryParse(s, out d))
{
return d;
}
else
{
message = String.Format("\"{0}\" is not a valid date.", s);
return null;
}
}
}
一個易於谷歌問題的例子,如果有人問今天會因「沒有足夠的研究」而不公平地關閉。 – 2013-06-27 20:39:56
這裏是一個簡單的方法來做到這一點,而不使用任何特殊的功能: –
xameeramir
2013-09-11 16:20:15