c#中的日期时间分析器错误

本文关键字:分析器 错误 时间 日期 | 更新日期: 2023-09-27 18:09:44

t_info.solutionTime = Convert.ToDateTime(context.Request.QueryString["solutionDate"] == null ? "" : context.Request.QueryString["solutionDate"]);

我试图转换日期格式,但它总是返回这个异常

系统。FormatException:字符串未被识别为有效的日期时间

日期格式:2015-08-25 18:45:55

c#中的日期时间分析器错误

可能是因为""不是有效的日期/时间值。您可以使用DateTime.MinValue或其他一些"魔法"值来代替null:

t_info.solutionTime =
    context.Request.QueryString["solutionDate"] == null 
  ? DateTime.MinValue 
  : Convert.ToDateTime(context.Request.QueryString["solutionDate"]);

我建议您使用DateTime。当您不确定传入值是否是有效日期时,尝试解析。

DateTime possibleDateTime;
if (!DateTime.TryParse(context.Request.QueryString["solutionDate"], out possibleDateTime))
{
    //handle the situation where the parse fails
}
//if you get here you know there's a valid datetime in possibleDateTime