我在查询字符串中传递了一个日期作为02-2014的格式.使用这个日期我完成了搜索.它正在工作,结果很完美.但是当我在浏览器中更改查询字符串值时,错误将显示在这种情况下我只需要一些消息,那么我们如何检查查询字符串的日期值是否格式正确.我的代码是
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Run Code Online (Sandbox Code Playgroud)
只需使用DateTime.TryParseExact格式字符串MM-yyyy.这将告诉您输入字符串是否是您指定的格式,如果是,它将通过out参数返回已解析的DateTime对象.