这个问题可能听起来很愚蠢,但我尝试了所有不同的方式,因为我想验证日期或日期时间的不同格式,如果格式无效则记录错误。
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
}
任何人都可以帮我解决这个问题吗?欢呼声。
答案 0 :(得分:3)
看来,您不需要正则表达式:尝试解析并查看它是否成功:
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
}