这个问题听起来很傻,但我尝试了各种不同的方法,因为我想验证不同格式的日期或日期-时间,并记录错误的格式是无效的。
Example: 10 March 2016, 10 Mar 16, 10 Mar 2016
我尝试使用正则表达式,但它只是检查正常的日期、日期时间格式,比如DD/MM/YYYY
、YYYY/MM/DD
、DD-MM-YYYY
等等。
这是我的代码:
bool isDate = Regex.IsMatch(Value.ToString(), @"^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$");
if (isDate == true)
{
DateTime datetime;
DateTime.TryParse(Value.ToString(), out datetime);
sGetDate = datetime.ToString("dd/MM/yyyy");
GetString.Add(sName + ":" + sGetDate);
}
else{
//log error
}
有人能帮我解决这个问题吗?干杯。
发布于 2016-10-06 09:47:22
看起来,您不需要使用正则表达式:尝试解析并查看它是否成功:
string source = "10 Mar 16";
...
// Put all allowed formats here
string[] formats = new string[] {
"d MMMM yyyy",
"d MMM yyyy",
"d MMM yy"
};
if (DateTime.TryParseExact(source,
formats,
CultureInfo.InvariantCulture, //TODO: may be you want CultureInfo.CurrentCulture
DateTimeStyles.AssumeLocal,
out datetime)) {
// datetime contains valid date and time
}
else {
// log error: parsing fails
}
https://stackoverflow.com/questions/39892633
复制相似问题