使用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